else..if ladder


else..if ladder

When a series of many conditions have to be checked we may use the ladder else if statement which takes the following general form. This construct is known as if else construct or ladder. The conditions are evaluated from the top of the ladder to downwards. As soon as the TRUE condition is found from top onwards, The statements associated with it are executed otherwise i.e. if all conditions fails, the default-statement will be executed and control is transferred to Next-statement.

if(cond 1) 
   statement – 1;
else if (cond 2) 
   statement – 2;
.
else if (cond n) 
   statement – n;
else
   default-statement;
Next-statement;

Sample Program to print the grade of student based on his percenatge.


#include<stdio.h>
#include<conio.h>
void main ()
{
            int marks;
            printf ("Enter marks: ");
            scanf ("%d", &marks);
            if (marks <= 100 && marks >= 70)
                        printf ("\n Distinction");
            else      if (marks >= 60)
                        printf ("\n First Class");
            else      if (marks >= 50)
                        printf ("\n Second Class");
else      if (marks >= 40)
                        printf ("\n Third Class");
            else      printf ("\n Fail");
}

Output:-
Enter Marks: 73
Distinction


No comments:

Post a Comment