loading...

Conditions

giladri profile image Gilad Ri Updated on ・5 min read

C-mpler (13 Part Series)

1) C-mpler Introduction 2) Basic Variables & Operators 3 ... 11 3) Intro to I/O 4) Conditions 5) Practice #1 6) Loops 7) Compilation & Precompilation 8) Static Arrays 9) Practice #2 10) Memory Addresses & Pointers 11) Memory Allocation & Dynamic Arrays 12) Basic Sorting 13) Recursion

Ok, we already learned how to create some variables, and how to change their values (even in an interactive away). But, what if we want to check some conditions about their value?

For this case in most of the programming languages, we have the if statement:

if ([some_condition_statment]) {
    // The conditional statement proved true - do something about that
}

If we want to do something if the conditional statement proved, and something else if not, we have to use the else statement:

if ([some_condition_statment]) {
    // True - do something about that
} else {
    // False - do something else
}

But, what we can check? To answer this we need to learn about the comparison operators:

Comparison Operators

  • "==": checks if the two operands are equal.
  • ">=": checks if the left operand is bigger or equal to the right operand.
  • "<=": checks if the left operand is smaller or equal to the right operand.
  • "!=": checks if the two operands are different.
  • ">": checks if the left operand is bigger than the right operand.
  • "<": checks if the left operand is smaller than the right operand.

For example:

#include <stdio.h>
int option;
// Asks for an input from the user
printf("Choose an option:\n");
scanf("%d", &option);
// Operates according to the user choice
if (option == 1) {
    printf("Hello\n");
} else {
    printf("Bye bye\n");
}

Notice, in C, each comparison operator returns 1 if the condition met and 0 otherwise. Therefore, if we want we can (but don't do that):

int x = 5;
int y = 5;
int z = (x==y); // z == 1

That means that the if statement just checks if the value between the brackets is 0 or different than 0 (even a negative number!). For example:

if (5) {
   // We will always enter this code block because 5 != 0
}

We should remember this trick for later.

Let's talk now about logical operators. Logical operators allow us to check whether two or more conditions are met (the AND operator), if at least one condition is met (the OR operator) or if some condition isn't met (the NOT operator).

Logical Operators

  • "&&": the AND operator. Checks whether both conditions are met.
  • "||": the OR operator. Checks whether at least one condition is met (can be both).
  • '!': the NOT operator. Checks whether a condition isn't met.

AND example:

#include <stdio.h>

int number;
// Gets a number from the user
printf("Enter a number between 1-10\n");
scanf("%d", &number)
// Checks if the number if in the range 1 - 10
if (number >= 1 && number <=10) {
    printf("OK\n");
} else {
    printf("The number is out of range\n");
}

OR example:

#include <stdio.h>

char option;
// Gets a character from the user
printf("Choose: 'q' or 'w'\n");
scanf("%c", &option)
// Checks if the optin is legal
if (option == 'q' || option == 'w') {
    printf("OK!\n");
} else {
    printf("Invalid option!\n");
}

NOT example:

#include <stdio.h>

// Initializes a variable
int x = 10;

int a = !x; // a == 0 because '!' makes every number, (other than 0), to be 0
int b = !a; // b == 1 because '!' makes 0 to be 1

b = !b // b == 0

if (!b) {
    printf("b's value is 0\n"); // This will be printed!
}

The last example is a little weird, but you can learn a lot from it and it's probably the most important example of all three. We will see that the '!' operator is really useful when we want to check whether a variable's value is 0 (or NULL).

Switch-Case

Ok, now we go on to another topic: what if we want to check a lot of conditions? In this case, we can write a code like this:

#include <stdio.h>

int option;
// Asks for input from the user
printf("Choose an option:\n");
scanf("%d", &option);
// Operates according to the user choice
if(option == 1) {
    printf("You look awesome!\n");
} else if (option == 2) {
    printf("Have a nice day!\n");
} else if (option == 3) {
    printf("Nice to meet you!\n");
} else {
    printf("Invalid option\n");
}

But this is really ugly and difficult to change if we want to in the future. Therefore, in this case, we use the switch statement as follows:

switch([variable]) {
case [first_value]:
    // Code
    break;
case [second_value]:
    // Code
    break;
default:
    // The code which we want to run if no condition met until the end
    break;

For example:

#include <stdio.h>

int option;
// Asks for input from the user
printf("Choose an option:\n");
scanf("%d", &option);
// Operates according to the user choice
switch(option) {
case 3:
    printf("Nice to meet you!\n");
case 2:
    printf("Have a nice day!\n");
    break;
case 1:
    printf("You look awesome!\n");
    break;
default:
    printf("Invalid option\n");
    break;
}

This code does the same as the if-else code from above does, and it looks prettier and easier to understand. Each case is just like:

if ([variable] == [value])

Let's talk about the break keyword. This keyword means: "Get out from this block of code!". What is a block of code? Simply put, everything that is inside curly brackets. In this case, the code between the brackets is the switch-case, and therefore the break just makes us jump to the last row of our code.

"Why do we use break?" you suppose to ask. The answer is simple: because that how switch-case works. If we don't write a break, the code just goes on and run all the lines until the end of the switch-case - what means all the code lines that are for the cases which are below the case we entered.
This might sound odd, but it does have some use cases. (I admit that I can't think about many use cases, but I found some, I promise you). For example, if we don't know what is "loop" (as we really are, right now), we can still print a stuff a lot of times according to our choice (with a limit) using this trick:

#include <stdio.h>

int times;
// Asks for input from the user
printf("Choose the number of times:\n");
scanf("%d", &times);
// Operates according to the user choice
switch(times) {
case 5:
    printf("Hi\n");
case 4:
    printf("Hi\n");
case 3:
    printf("Hi\n");
case 2:
    printf("Hi\n");
case 1:
    printf("Hi\n");
default:
    break;
}

For the input 3 will be printed:

Hi
Hi
Hi

Thats because we enter to the case where times is 3, and then go on to the next line (the printf of the case for 2) and then to the next line (the printf of the case for 1) and then we breaks at the default case. To be clear: we ignore the "cases" lines, and just run the code lines which "inside" them (after we enter at least one case, or the default case).

Finally, to the default keyword: we enter this case if we enter none of the cases above. That's all for now, keep having fun.

Always remember, it's much C-mpler than you thought!

Regards,
Gilad

C-mpler (13 Part Series)

1) C-mpler Introduction 2) Basic Variables & Operators 3 ... 11 3) Intro to I/O 4) Conditions 5) Practice #1 6) Loops 7) Compilation & Precompilation 8) Static Arrays 9) Practice #2 10) Memory Addresses & Pointers 11) Memory Allocation & Dynamic Arrays 12) Basic Sorting 13) Recursion

Posted on by:

Discussion

markdown guide