Table of Contents
In this lesson, we will be learning about if/else control flow statements in C with examples. If/else statements are a form of flow control statements that help you modify the flow based on specific conditions.
Syntax of if-else Statement in C
if (condition1) { // execute code if contirion 1 is true } else if (condition2) { // execute code if contirion 2 is true } else { // execute if both conditions are false }
if-else Statement Flowchart
if Statement
“If” accepts a Boolean value (True or False). The ‘if’ statement will be executed if the conditional statement inside is true
Example of if Statement in C
#include <stdio.h> int main( ) { int i = 12; if(i > 10){ // true as 12 is greater than 10 printf("i is greater than 10"); } return 0; }
Output
i is greater than 10
‘else if’ statement:
else-if is used to check another condition after the initial ‘if’ statement. the compiler will execute the code inside the statement if the first condition is false and the conditional statement is true.
Example of else-if Statement in C
#include <stdio.h> int main( ) { int i =12; if(i < 10){ // false as 7>5 printf("i is lesser than 5"); // this code will not be executed } else if(i > 10){// true as 12 > 5 printf("i is greater than 5"); } return 0; }
Output
i is greater than 5
else Statement in C
The ‘else statement’ doesn’t take any values. This statement block will be executed if all other ‘if’ or ‘else if’ conditions are false.
Example of else statement in C
#include <stdio.h> int main( ) { int i = 10; //defining variable and assigning a value to it if(i<10) { // false printf("i is lesser than 5"); // Will be be executed } else if( i>10 ){// false printf("i is greater than 5"); // Will be be executed } else { // true as both conditions above are false printf("This Statement is True"); } return 0; }
Output
This Statement is True
Nested if-else Statements in C
In case of internal conditions within a given condition, it is better to use Nested if-else statements. All the rules mentioned above apply here too.
#include <stdio.h> int main( ) { int i = 1; //defining variable and assigning a value to it if (i >= 0) { if(i < 5){ //true as 1 < 5 printf("i is lesser than 5 so entering in if in the first if"); } else if(i > 5){// false as 1 < 5 printf("i is greater than 5 so entering in else if"); } else {// true as 1 != 5 printf("i is equal to 5"); } } else{ printf("Entered a -ve number"); } return 0; }
Output
i is lesser than 5 so entering in if in the first if
Summary
- ‘If else’ statements are used to control the flow of our application code.
- ‘If’ and ‘else if’ take a Boolean argument and if it is true then the if or else if is executed.
- ‘if’ can be used independently, but else if or else requires a preceding if for proper execution.
- Multiple ‘else if’ statements can be used, in such a scenario it is called an ‘else-if ladder’.