Nested if-else statements in C language
If-else statements that are nested inside of one another are a form of conditional statement used in the C programming language. The programmer can check for many conditions using nested if-else statements, and depending on the outcome of each condition, execute different code blocks.
Syntax of nested if-else statement:
if (condition1)
{
// code to be executed if condition1 is true
if (condition2)
{
// code to be executed if both condition1 and condition2 are true
}
else
{
// code to be executed if condition1 is true and condition2 is false
}
}
else
{
// code to be executed if condition1 is false
}
We can see from this syntax that there is an outer if statement that performs a conditional check. The code inside the outer if statement will be executed if the condition is met. The inner if statement, on the other hand, is contained within the outer if statement. The inner if clause looks for a different circumstance. The inner if statement’s code will be executed if this condition is met. The code included inside the inner else statement will be executed if the condition is false.
Example of a nested if-else statement
#include <stdio.h>
int main() {
int age;
printf("Enter your age: ");
scanf("%d", &age);
if (age >= 18) {
if (age >= 60) {
printf("You are a senior citizen.");
}
else {
printf("You are an adult.");
}
}
else {
printf("You are a minor.");
}
return 0;
}
Output:
Enter your age: 65
You are a senior citizen.
Enter your age: 15
You are a minor.
In the above example, we take input of age from the user and then check if the age is greater than or equal to 18 using the outer if statement. If it is, then we check if the age is greater than or equal to 60 using the nested if statement. If it is, then we print “You are a senior citizen.” If it is not, then we print “You are an adult.” If the age is less than 18, then we print “You are a minor.” This is an example of a nested if-else statement.
#include <stdio.h>
int main() {
int num;
printf("Enter a number between 1 and 100: ");
scanf("%d", &num);
if (num > 0) {
if (num <= 50) {
printf("The number you entered is between 1 and 50.\n");
}
else {
printf("The number you entered is between 51 and 100.\n");
}
}
else {
printf("The number you entered is not between 1 and 100.\n");
}
return 0;
}
Output:
Enter a number between 1 and 100: 25
The number you entered is between 1 and 50.
//If the user enters a number between 51 and 100, the output will be:
Enter a number between 1 and 100: 75
The number you entered is between 51 and 100.
//If the user enters a number less than or equal to 0, the output will be:
Enter a number between 1 and 100: -5
The number you entered is not between 1 and 100.