If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In C programming, a "nested if-else" statement is used when an "if-else" statement is placed inside another "if-else" statement. This allows for multiple levels of conditions to be checked. The syntax for a nested if-else statement is as follows:
Copy code
if (condition1) {
// code to be executed if condition1 is true
if (condition2) {
// code to be executed if 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
}
Here is an example of a program that uses a nested if-else statement to check the eligibility of a voter based on their age and citizenship:
Copy code
#include <stdio.h>
int main() {
int age;
char citizen;
printf("Enter your age: ");
scanf("%d", &age);
printf("Are you a citizen? (y/n): ");
scanf(" %c", &citizen);
if (age >= 18) {
if (citizen == 'y') {
printf("You are eligible to vote.");
} else {
printf("You are not a citizen. You are not eligible to vote.");
}
} else {
printf("You are not 18 yet. You are not eligible to vote.");
}
return 0;
}
In this example, the program prompts the user to enter their age and citizenship. The outer if statement checks if the age is greater than or equal to 18. If the age is greater than or equal to 18, the inner if statement checks if the user is a citizen. If the user is a citizen and age is greater than or equal to 18, the program prints "You are eligible to vote." If the user is not a citizen or age is less than 18, the program prints "You are not a citizen. You are not eligible to vote." or "You are not 18 yet. You are not eligible to vote." respectively.
Nested if-else statements can be useful when you need to check multiple conditions and take different actions based on the combination of those conditions.
Comments: 0