C programming if statement multiple conditions: The nested if statement in C programming language is used when multiple conditions need to be tested. The inner statement will execute only when outer if statement is true otherwise control won’t even reach inner if statement.
Syntax of Nested If Statement
if(condition_expression_one) { /* Code to be executed when condition_expression_one is true */ statement1; if(condition_expression_two) { /* Code to be executed when condition_expression_one and condition_expression_two both are true */ statement2; } }
If the condition_expression_one is true, then statement1 is executed and inner if statements condition_expression_two is tested. If condition_expression_two is also true then only statement 2 will get executed.
C Program to show use of Nested If Statements to test multiple conditions
#include<stdio.h> #include<conio.h> int main(){ int num; printf("Enter a numbers\n"); scanf("%d", &num); /* Using nested if statement to check two conditions*/ /* Outer if statement */ if(num < 500){ printf("First Condition is true\n"); if(num > 100){ printf("First and Second conditions are true\n"); } } printf("This will print always\n"); getch(); return(0); }
Output
Enter a numbers 80 First Condition is true This will print always
Enter a numbers 200 First Condition is true First and Second conditions are true This will print always
Enter a numbers 800 This will print always
Points to Remember about Nested If Statement
- The condition_expression is a boolean expression. It must evaluate to true or false value(In C, all non-zero and non-null values are considered as true and zero and null value is considered as false).
- We may use more than one condition inside nested if statement
For Example:
if(condition_one && condition_two) {
if(condition_three) {
/* put statements here */
}
} - Opening and Closing Braces are optional, If the block of code of nested if statement contains only one statement.
For Example:
if(condition_expression)
if(condition_expression)
statement1;
In above example, statement1 will gets executed if both if conditions are true.