C – If-Else Statement
The if-else statements are used to run specific code based on condition. The if statement executes a statement if a specified condition is true. If the condition is false, another statement can be executed. Basically, there are 4 types of if statements.
- if statement
- if-else statement
- if-else-if ladder statement
- nested if statement
1. if Statement
An if statement evaluates the expression written inside the parenthesis.
if (Expression) { // statement block }
If the expression returns true, The if statement block will be executed. If the expression return false (zero), the statement block will be skipped.
Example: if Statement
The following program with input a number from the user and check if the number is less than 10.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | // The C programme to input number from user // Check if number is less than 10 #include <stdio.h> void main() { int num; printf("Enter an number: "); scanf("%d", &num); if (num < 10) { printf("num is less than 10); } } |
2. if-else Statement
An if statement evaluates the expression and execute the statements based on results.
if (Expression) { // if statement block } else { // else statement block }
If the expression returns true, The if statement block will be executed. If the expression return false (zero), the else statement block will be executed.
Example: if-else Statement
The following program with input a number from the user and check if the number is less than 10.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | // The C programme to input number from user // Check if given number is even or odd #include <stdio.h> void main() { int num; printf("Enter an number: "); scanf("%d", &num); if(num % 2 == 0) printf("%d is even number", num); else printf("%d is odd number", num); } |
3. if-else-if Statement
An if statement evaluates the expression and executes the statements based on results.
if (Expression) { // statement 1 } else if (Expression) { // statement 2 }
If the expression returns true, The statement 1 block will be executed. If the expression return false (zero), the control go to else and again evaluates a expression.
Example: if-else-if Statement
The following program with input a number from the user and check if the number is less than 10.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | // The C programme to input 2 numbers from user // Check which number is greater than other #include <stdio.h> void main() { int num1; int num2; printf("Enter first number: "); scanf("%d", &num1); printf("Enter second number: "); scanf("%d", &num2); if(num1 > num2 ) { printf("%d is greater than %d number", num1, num2); } else if(num2 > num1 ) { printf("%d is odd number", num2, num1); } } |