Nested IF and ELSE IF Ladder
iii. Nested IF....ELSE
General Form:
Sample Program : Find the largest among three input numbers.
iv. ELSE .... IF LADDER
General Form:
Sample Program : Program to read two numbers and an operator which performs the specified operation and display the result.
General Form:
if(conditional-expression) { if(conditional-expression) { statements; } else { statements; } statements; } else { if(conditional-expression) { statements; } statements; }In Nested if ..... else, the if and else part can contain one or more if else statements.
Sample Program : Find the largest among three input numbers.
1: #include<stdio.h> 2: #include<conio.h>3: void main()
4: {5: int a,b,c;
6: clrscr();7: printf("Enter two numbers : ");
8: scanf("%d%d,%d",&a,&b,&c);
9: if(a>b)
10: {11: if(a>c)
12: {13: printf("%d is largest",a);
14: }15: else
16: {17: printf("%d is largest",c);
18: } 19: }20: else
21: {22: if(b>c)
23: {24: printf("%d is largest",b);
25: }26: else
27: {28: printf("%d is largest",c);
29: } 30: } 31: getch(); 32: }iv. ELSE .... IF LADDER
General Form:
if(test condition) { } else if(condition) { } else if(condition) { } else { }This construct is known as the else if ladder. The conditions are evaluated from the top of the ladder downwards. As soon as a true condition is found, the statement associated with it is executed skipping the rest of the ladder.
Sample Program : Program to read two numbers and an operator which performs the specified operation and display the result.
1: #include<stdio.h> 2: #include<conio.h>3: void main( )
4: {5: float a,b,res;
6: char op;
7: clrscr( );8: printf("Enter two Numbers : ");
9: scanf("%d%d",&a,&b);
10: printf("Enter the Operator : ");
11: scanf("%c",&op);
12: if(op=='+')
13: res=a+b;14: else if(op=='-')
15: res=a-b;16: else if(op=='*')
17: res=a*b;18: else if(op=='/')
19: res=a/b;20: else
21: {22: printf("Invalid Operator ! \n Press any key to exit...");
23: getch( ); 24: exit(0); 25: }26: printf("%.2f %c %.2f = %.2f",a,op,b,res );
27: getch( ); 28: }

