Thursday, 5 March 2015

The if-else-if Ladder in C

In certain cases multiple conditions are to be detected. In such cases the conditions and their associated statements can be arranged in a construct that takes the form:

if (condition-1)
statement-1;
else if (condition-2)
statement-2;
else if (condition-3)
statement-3;
else
statement-n;

The above construct is referred as the if-else-if ladder. The different conditions are evaluated starting from the top of the ladder and whenever a condition is evaluated as TRUE, the corresponding statement(s) are executed and the rest of the construct it skipped.

Example 4.3 – Write a program to display the student’s grade based on the following table:

Marks          Grade
>=75              A
> 50 and <75  B
> 25 and <50  C
< 25                F

In this case multiple conditions are to be checked. Marks obtained by a student can only be in one of the ranges. Therefore if-else-if ladder can be used to implement following program.

/* Program-4.5 */
#include <stdio.h>
int main()
{
int marks;
printf("Enter marks: ");
scanf("%d", &marks); //read marks
if(marks > 75) // if over 75
printf("Your grade is: A");
else if(marks >= 50 && marks <75) // if between 50 & 75
printf("Your grade is: B");
else if(marks >= 25 && marks <50) // if between 25 & 50
printf("Your grade is: C");
else
printf ("Your grade is: F"); // if less than 25
return 0;
}

Notice that in Program-4.5, some of the conditional expressions inside the if clause are not as simple as they were earlier. They combine several expressions with logical operators such as AND (&&) and OR (||). These are called compound relational tests.

Due to the top down execution of the if-else-if ladder Program-4.5 can also be written as follows:

/* Program-4.6 */
#include <stdio.h>
int main()
{
int marks;
printf("Enter marks: ");
scanf("%d", &marks); //get marks
if(marks > 75)
printf("Your grade is A"); // if over 75
else if(marks >= 50 )
printf("Your grade is B"); // if over 50
else if(marks >= 25 )
printf("Your grade is C"); // if over 25
else
printf ("Your grade is F"); // if not
return 0;
}

In Program-4.6, when the marks are entered from the keyboard the first expression (marks > 75) is evaluated. If marks is not greater than 75, the next expression is evaluated to see whether it is greater than 50. If the second expression is not satisfied either, the program evaluates the third expression and so on until it finds a TRUE condition. If it cannot find a TRUE expression statement(s) after the else keyword will get executed.


No comments:

Post a Comment