Thursday, 28 October 2010

Nested if...else statement (if...else if....else Statement)



Nested if...else statement (if...elseif....else Statement)

The nested if...else statement is used when program requires more than one test expression.
Syntax of nested if...else statement.
if (test expression1){
     statement/s to be executed if test expression1 is true;
     }
     else if(test expression2) {
          statement/s to be executed if test expression1 is false and 2 is true;
     }
     else if (test expression 3) {
         statement/s to be executed if text expression1 and 2 are false and 3 is true;
     }
         .
         .
         .
     else {
            statements to be executed if all test expressions are false;
       }
How nested if...else works?
The nested if...else statement has more than one test expression. If the first test expression is true, it executes the code inside the braces{ } just below it. But if the first test expression is false, it checks the second test expression. If the second test expression is true, it executes the statement/s inside the braces{ } just below it. This process continues. If all the test expression are false, code/s inside else is executed and the control of program jumps below the nested if...else
The ANSI standard specifies that 15 levels of nesting may be continued.
Example 3: C nested if else statement


Write a C program to relate two integers entered by user using = or > or < sign.
#include <stdio.h>
int main(){
     int numb1, numb2;
     printf("Enter two integers to check\n");
     scanf("%d %d",&numb1,&numb2);
     if(numb1==numb2) //checking whether two integers are equal.
          printf("Result: %d = %d",numb1,numb2);
     else
        if(numb1>numb2) //checking whether numb1 is greater than numb2.
          printf("Result: %d > %d",numb1,numb2);
        else
          printf("Result: %d > %d",numb2,numb1);
return 0;
}
Output 1
Enter two integers to check.
5
3
Result: 5 > 3
Output 2
Enter two integers to check.
-4
-4
Result: -4 = -4

programs on else if

1. write a program to find the average, grade of the 3 subjects using if ..else

Conditional statements

No comments:

Post a Comment