if else ladder in c Language

Given Diagram is for the flowchart of the if-else Ladder statement.
The Flow chart shows working of if-else-if Ladder in C Programming.
if the Condition1 is TRUE then the Statement1 will be executed and control goes to next statement in the program following if-else-if ladder.
If Condition1 tested is FALSE only then Condition2 will be tested, if Condition2 is TRUE then Statement2 will be executed and control goes to next statement .
Similarly, if Condition2 is FALSE then next condition will be checked and the process continues.
If all the conditions in the if-else-if ladder are evaluated to FALSE, then Default Statement will be processed.


Example 1: C program to illustrates the use of if-else-if ladder statement .

/* C program to find maximum number out of 4 given numbers */
#include<stdio.h>
int main()
{
int p,q,r,s;
printf("\n Enter any four numbers");
scanf("%d%d%d%d",&p,&q,&r,&s);
if(p>q && p>r && p>s)    /*test p largest */
 {
  printf("\n %d is Maximum number",p);
 }
else if (q>p && q>r && q>s)    /*else test q is largest*/
 {
  printf("\n %d is Maximum number",q);
 }
else if (r>p && r>q && r>s)    /*else test r is largest */
 {
  printf("\n %d is Maximum number",r);
 }
else
 {
  printf("\n %d is Maximum number",s);
  }
return 0;
}

Output:
Enter any four numbers
5
7
1
8
8 is Maximum number.



Program Explanation:
The above program illustrates the use of if-else-if ladder statement to find maximum number out of given four number.
1. In the above program, we have declared integer variables int p,q,r,s ; to store integer values.
2. Then, we have used printf("\n Enter any four numbers");
scanf("%d%d%d%d",&p,&q,&r,&s);
Which shows the message "Enter any four number" on console and control waits until we do not enter any four number, then we entered numbers are
5
7
1
8
The Entered numbers get stored in variable p, q, r, s respectively by scanf("%d%d%d%d",&p,&q,&r,&s);
3. Then, we have used if with a test-expression to check whether the number in variable p is the maximum by using if(p>q && p>r && p>s).
Here the test expression evaluates to false i.e. p=5 is not greater than any of the variables so control jumps to next else-if block
4. and test the condition else if (q>p && q>r && q>s). which is again false because q=7 is not greater than any of the values or variable, control again jumps to next else-if block.
5.and start executing the condition else if (r>p && r>q && r>s). which is again evaluates to false i.e. r=1 is not greater than any other values and finally else block executes. Control transfer to else block.
5.else the statements inside the else block executes
i.e. printf("\n %d is Maximum number",s);
and gives final output 8 is Maximum number


Previous Topic:-->> if else statement in C || Next topic:-->>Nested if else in C.