Nested If Else with Example In C Language

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

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.

5. Flow Control

Comments: 0

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?