C Nested if else Statement

Nested IF ELSE statement in c programming; In this tutorial, i am going to show you how to use if else, nested if else statements in C programming with examples.

C Nested if else Statement

In c programming, A nested if statement is an if-else statement with another if statement as the if the body or the else body.

Syntax of C Nested if else Statement

The syntax of the nested if else statement in C programming; as shown below:

if(condition) {
    //Nested if else inside the body of "if"
    if(condition2) {
       //Statements inside the body of nested "if"
    }
    else {
       //Statements inside the body of nested "else"
    }
}
else {
    //Statements inside the body of "else"
}

Example 1 – Nested if…else

See the following c program for Nested if else statement; as shown below:

#include <stdio.h>
int main() {
    int number1, number2;
    printf("Enter two integers: ");
    scanf("%d %d", &number1, &number2);
    if (number1 >= number2) {
      if (number1 == number2) {
        printf("Result: %d = %d",number1,number2);
      }
      else {
        printf("Result: %d > %d", number1, number2);
      }
    }
    else {
        printf("Result: %d < %d",number1, number2);
    }
    return 0;
}

Output of the above c program

Enter two integers: 10 5
Result: 10 > 5

Explaination of above c program

  • Take two input number from user in program.
  • Then the test expression using nested if else statement in c program.
  • Print result

Example 2 – C program for leap year using nested if elseusing if else statement

See the second c program for leap year using nested if else; as shown below:

#include <stdio.h>
int main()
{
    int y;

    printf("Enter year: ");
    scanf("%d",&y);

    if(y % 4 == 0)
    {
    	//Nested if else
        if( y % 100 == 0)
        {
            if ( y % 400 == 0)
                printf("%d is a Leap Year", y);
            else
                printf("%d is not a Leap Year", y);
        }
        else
            printf("%d is a Leap Year", y );
    }
    else
        printf("%d is not a Leap Year", y);

    return 0;
}

Output of the above c program

Enter year: 2022
2022 is not a Leap Year

Explanation of above c program

  • Take input year from user in c program.
  • Use nested if else statement to check whether a given year is leap or not
  • Print result.

More C Programming Tutorials

Leave a Comment