## Conditional operations in C programming

Computer programs generally perform conditional operations for basic decision-making. A conditional is a statement that causes a program to execute in a certain way if a specific condition has been met.

Before we get deep into conditional statements, lets us first understand how logical relations work in C. Unlike most high level programming languages, C has no built-in boolean data type and this results in C treating logic as being arithmetic. As a result, in C, the value 0 (zero) represents false, and all other values represent true.

### Relational and equality expressions

Relational expressions are used to compare values and equality expressions are used to check equality of values.

ExpressionDescription
a < breturns 1 if a is less than b, 0 otherwise.
a > breturns 1 if a is greater than b, 0 otherwise.
a <= breturns 1 if a is less than or equal to b, 0 otherwise.
a >= breturns 1 if a is greater than or equal to b, 0 otherwise.
a == breturns 1 if a is equal to b, 0 otherwise.
a != breturns 1 if a is not equal to b, 0 otherwise.

Let us test by printing out the results of the expressions:

#include <stdio.h>

int main(){

int a = 2;
int b = 3;

// is a less than b?
printf("%d\n", a < b);		//> 1

// is a greater than b?
printf("%d\n", a > b);		//> 0

// is a less than or equal to b?
printf("%d\n", a <= b);		//> 1

// is a greater than or equal to b?
printf("%d\n", a >= b);		//> 0

// is a equal to b?
printf("%d\n", a == b);		//> 0

// is a not equal to b?
printf("%d\n", a != b);		//> 1

return 0;

}


The "equal to" operator is == and not =.

### Logical expressions

• a || b → returns 1 when EITHER a OR b is true (or both), otherwise the result is 0.
• a && b → returns 1 when BOTH a AND b are true, otherwise the result is 0.
• !a → returns 1 when a is false, the result is 0 otherwise.

## If statements in C

If statements provides a way to cause the program to execute a block of code only if certain conditions are met.

Syntax:

if (condition) {
//execute this code if condition is true
}


For example, lets us write a code that will decide whether a person is allowed to drive or not, based on the person’s age.

#include <stdio.h>

int main(){

int age;

scanf("%d", &age);

// test condition
if (age > 17){

// execute this part of the code if age is greater than 17
printf("Of course you can drive, afterall you are %d.", age);

// terminate the program
return 0;
}

// execute this part if age is not greater than 17
printf("At %d, I'm afraid you are too young to drive.", age);

// terminate the program
return 0;
}


Here is how the code will work:

• You will be prompted to enter you age
• The age you enter will be taken in and compared against 17 in the if condition.
• If the age is greater than 17, the code inside the if block will be executed and return 0 will then terminate the program before the rest of the code is executed.
• This will make sure only the code inside the if block is executed.
• However, if the age is not greater than 17, the code inside the if block wont be executed. The return 0 inside the if block wont be executed. The whole if block is skipped because the condition is false.
• This time the code outside the if block will be executed.

One important thing to note about a return statement is that it breaks us out of a function. In our example return 0 breaks us out of the main function and thereby terminating the program.

## If-else statements in C

If-else statements provides a way to cause the program to execute a block of code only if certain conditions are met and also a way to execute another block of code if conditions are not met.

Syntax:

if (condition) {
//execute this part if condition is true
} else {
//execute this part if the condition is not true
}


For example, lets us write a code that will decide whether a person has passed or not, based on the person’s mark.

#include <stdio.h>

int main(){

int mark;

scanf("%d", &mark);

// test condition
if (mark > 49){

// execute this part of the code if mark is greater than 49
printf("Congratulations you have passed.");

} else {

// execute this part if mark is not greater than 49
printf("I'm afraid you will have to rewrite the exam.");
}

// terminate the program
return 0;
}


The first block of code executes if the condition (mark > 49) is true, otherwise the second block (the else block) executes.

## else if statements in C

An if clause can directly follow an else clause if we want to test more conditions.

#include <stdio.h>

int main(){

int mark;

scanf("%d", &mark);

if(mark < 24) {

// if mark is less than 24
printf("You results are ungraded. I'm sorry you failed.");

} else if(mark >= 24 && mark < 40){

// if mark is between 24 and 40
printf("You failed with an E. You really need to work hard");

} else if(mark >= 40 && mark < 50){
// if mark is btwn 40 and 50
printf("You failed with a D. You were almost there, better luck next time");

} else if(mark >= 50 && mark < 60){
// if mark is btwn 50 and 60
printf("You passed with a C. I beleive you can do better than that.");

} else if(mark >= 60 && mark < 70){
// if mark is btwn 60 and 70
printf("You passed with a B. Congratulations.");

} else {
// if mark is 70 and above

}

return 0;

}



While this looks useful, chaining more than two or three if-elses in this fashion is considered bad programming practice. A Switch-Case construct is preferred.

## Switch-case statements in C

A switch statement allows a variable to be tested for equality against a list of cases. If the value matches the case, the code corresponding to that case is executed.

Syntax:

switch(value){
case case1 : /* code to be executed if case1 is matched */
break;

case case2 : /* code to be executed if case2 is matched */
break;

/* you can have any number of case statements */

default : /* code to be executed if no case is matched */
}


The break clause stops the switch if the a case is matched. At the end of the cases we have the default case that is executed if no case is matched. For example:

#include <stdio.h>

int main(){

int num;

printf("Pliz enter a rating between 1 and 5 :\n");
scanf("%d", &num);

switch(num){
case 1: printf("Poor rating. We should redesign our product.");
break;

case 2: printf("Not bad, but maybe there is somewhere we can improve.");
break;

case 3: printf("Average rating. We can do better in the next update.");
break;

case 4: printf("Good experience. We will add some final touches.");
break;

case 5: printf("Excellent product. Looks like we did it.");
break;

default: printf("Invalid rating. Rating should be between 1 and 5");

}

return 0;

}


In the example code above, each case will be executed depending on the input. The output string will be:

• "Poor rating. We should redesign our product." if the input is 1.
• "Not bad, but maybe there is somewhere we can improve." if the input is 2.
• "Average rating. We can do better in the next update." if the input is 3.
• "Good experience. We will add some final touches." if the input is 4.
• "Excellent product. Looks like we did it." if the input is 5.
• Invalid rating. Rating should be between 1 and 5" if the input is any other number.

### Fallthrough in a switch-case

Fallthrough happens when there is no break after a case. The switch will continue executing even if a case has been matched. For example:

#include <stdio.h>

int main(){

int num;

printf("Pliz enter a day of the week between 1 and 7 :\n");
scanf("%d", &num);

switch(num){
case 1:

case 2:

case 3:

case 4:

case 5: {
printf("Weekday");
}
break;

case 6:

case 7: {
printf("Weekend");
}
break;

default: printf("Invalid day. There are 7 days in a week");

}

return 0;

}


In the example above:

• if the input is 1, the first case will be matched but since there is no break the execution will fallthrough until case 5 where it will print "Weekday" and then find a break. That is where the execution will stop. Same happens for all numbers before 5.
• case 6 will also fallthrough to case 7 where it will print "Weekend" before meeting break.

### Default case in a switch-case statement

The default case is very important because it executes when no case is matched. But however, the default case is optional. Even if the default case is absent, the switch will not throw an error if no case is matched. It will silently stop execution.

## The ternary operator in C

The ternary operator is a conditional that can be used in place of the if-else statement.

Syntax:

Condition ? Exp1 : Exp2;


Here is how it works. Condition is evaluated:

• If it is true, then Exp1 is evaluated.
• If it is false, then Exp2 is evaluated.

For example:

#include <stdio.h>

int main(){

(3 > 2)? printf("True"): printf("False");   // True

printf("\n");

(2 > 3)? printf("Yes"): printf("No");       // No

return 0;

}