Nested if Statements in C





In C programming, nested "if" statements are used to create a hierarchy of conditional statements. They allow you to have an "if" statement within another "if" statement, creating multiple levels of decision-making.

When you have complex conditions or situations where multiple conditions need to be evaluated, you can use nested "if" statements. Each "if" statement is enclosed within another "if" or "else" statement, creating a nested structure.

The nested "if" statements are executed based on the result of the outer "if" statements. If the condition of the outer "if" statement is true, the program evaluates the condition of the inner "if" statement. This process continues for each nested "if" statement.

Syntax

The syntax of nested "if" statements is as follows:

    if (condition1) {
      // code to execute if condition1 is true
      
      if (condition2) {
        // code to execute if condition1 and condition2 are true
        
        // nested "if" statements can continue further
      }
    }
    else {
      // code to execute if condition1 is false
    }
  


Example

Let's consider an example where we check if a number is positive and even:

    #include <stdio.h>

    int main() {
      int num;
      printf("Enter a number: ");
      scanf("%d", &num);
      
      if (num > 0) {
        if (num % 2 == 0) {
          printf("Number is positive and even.\n");
        }
        else {
          printf("Number is positive but not even.\n");
        }
      }
      else {
        printf("Number is not positive.\n");
      }
      
      return 0;
    }
  
output:
Enter a number: 52
Number is positive and even.
Enter a number: 51
Number is positive but not even.
Enter a number: -12
Number is not positive.

In this example, the program asks the user to enter a number. The program then uses nested "if" statements to determine if the number is positive and even.

If the number is greater than 0, the program evaluates the condition inside the nested "if" statement. If the number is divisible by 2 (i.e., it's even), it prints "Number is positive and even". Otherwise, it prints "Number is positive but not even".

If the number is not greater than 0, it directly prints "Number is not positive". The nested "if" statements allow the program to perform different checks based on the conditions in a hierarchical manner.

By using nested "if" statements, you can create complex decision-making structures in your C programs, allowing for more precise control and handling of different scenarios.