Sometimes we wish a multi - way decision based on several conditions. The most general way to doing this is by using the else if variant on the if statement. This works by cascading several comparisons. As soon as one of these gives a true result, the following statement or block is executed, and no further comparisons are performed. It consists of chain of ifs in. which the statement associated with each else is an if. The general form of else if ladder is as follows:
if (expression1)
statement – 1;
else if (expression 2)
statement -2;
else if (expression 3)
statement
. . . . . . . . . .
. . . . . . . . . .
else if (expression)
statement – n;
else
default – statement;
next statement;
The expression are evaluated from the top of the ladder, downwards. If the expression results non-zero, the statement associated are executed and the control is transferred to next statement skipping the rest of a ladder. When all the n-expressions results false, then the final else i.e., the default – statement is executed. Figure shows the logic of execution of else if ladder.
In the following example we are awarding grades depending on the examination result.
if (result >= 75)
printf (“passed: grade A\n”);
else if (result >= 60)
printf (“passed: grade B\n”);
else if (result >=45)
printf (“passed: grade c\n”);
else
printf (“failed\n”);
In this example, all comparisons test a single variable called result. In other cases, each test may involve a different variable or some combination of tests. The same pattern can be used be with more of fewer else if’s, and the final else may be left out. It is up to the programmer to devise the correct structure for each programming problem.
Program Calculate the commission for a sales representative as per the sales amount given below:
if sales <= Rs. 500, commission is 5%
if sales >500 and <=2000, commission is Rs. 35 plus 10%above Rs. 500
if sales > 2000 and <=5000, commission is Rs. 185 plus 12%above Rs. 2000
if sales > 5000, commission is 12.5%
#include <stdio. h>
#include <conio. h>
Main ()
{
int sales;
float comm;
clrscr ();
printf (“\nEnter the sales amount:”);
scanf (“%d”, &sales);
if (sales <= 500)
comm = 0.05*sales;
else
if (sales <=2000)
comm = 185 +o.12*(sales - 2000);
else
comm = 0.125*sales;
printf (“\nSales amount is %7d\n”, sales)
printf (“\nCommision amount is % 7.2f”, comm);
getch ()
}
Enter the sales amount: 4500
Sales amount is 4500
Commission amount is 485.00
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc