This blog is under construction

Saturday, 21 April 2012

Control statements - nested if statement

Syntax for Nested If:

if  (condition) {
     if  (Nested if's Condition) {
              <True Block>
     } else {
                 <False Block>
      }
} else {
    
     if  (Nested if's Condition) {
              <True Block>
     } else {
                 <False Block>
      }
}

If statement or if-else statement present inside another if or else block(as shown above) is called nested if statements.


Example C program using nested-if statement:
 
  #include <stdio.h>
  int main() {
        int num1, num2, num3;
        printf("Enter 3 numbers:");
        scanf("%d%d%d", &num1, &num2, &num3);
        if (num1 > num2) {  // expression for if statement
                if (num1 > num3) {   // nested if -> if statement inside another if block
                        printf("%d is greatest\n", num1);
                } else {
                        printf("%d is greatest\n", num3);
                }
        } else {
                if (num2 > num3) {  // nested if -> if statement inside another else block
                        printf("%d is greatest\n", num2);
                } else {
                        printf("%d is greatest\n", num3);
                }
        }
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter 3 numbers:10 20 30
  30 is greatest



No comments:

Post a Comment