Lecture 10 – Decisions (if-else-if)



if-else-if


Consider a scenario where we have to check multiple conditions which are related to each other. For example we enter marks of a student and then we assign a grade to it.

Marks
Grade
>=80
A
>=70 and <80
B
>=60 and <70
C
>=50 and <60
D
<50
Fail

 

In above scenario, if we use simple if then we need to use FIVE if statements. These if’s would be checked every time, even if the first condition is true.

Syntax


if(condition)

{

// Statements if true

}

else if (condition)

{

//Statements if true

}

else if (condition)

{

//Statements if true

}

else if (condition)

{

//Statements if true

}

else if (condition)

{

//Statements if true

}

.

.

else

{

}

 

With à if
Example 19 - Grading system using if
With à if-else-if
Example 20 - Grading system using if-else-if
 
#include <stdio.h>
#include <conio.h>

Output
Please enter your marks: 79
Grade B
 
 



void main()
{
 
int marks;
clrscr();                                                                                                
printf(“\nPlease enter your marks: ”);
scanf(“%d”, &marks);
 
if(marks>=80)
{
printf(“\nGrade A”);
}
 
if(marks >= 70 && marks < 80)
{
printf(“\nGrade B”);
}
 
if(marks >= 60 && marks < 70)
{
printf(“\nGrade C”);
}
 
if(marks >= 50 && marks < 60)
{
printf(“\nGrade D”);
}
 
if(marks < 50)
{
printf(“\nFail  :(”);
}
 
getch();
}
 
#include <stdio.h>
#include <conio.h>

Output
Please enter your marks: 79
Grade B
 
 

void main()
{
 
int marks;
clrscr();                                                                                                
printf(“\nPlease enter your marks: ”);
scanf(“%d”, &marks);
 
if(marks>=80)
{
printf(“\nGrade A”);
}
 
else If(marks >= 70 && marks < 80)
{
printf(“\nGrade B”);
}
 
else if(marks >= 60 && marks < 70)
{
printf(“\nGrade C”);
}
 
else if(marks >= 50 && marks < 60)
{
printf(“\nGrade D”);
}
 
else
{
printf(“\nFail  :(”);
}
getch();
}

Table 7 - Comparison of if and if-else-if

With if, the program will check each and every condition, every time; but in the case of if-else-if if the first condition is true, then the rest of the conditions would not be checked. Notice else at the end of the code. Make sure that after your else-if’s there’s else at the end. If compiler doesn’t find else at the if-else-if block; it is considered as a syntax error.

Comments

Popular posts from this blog

Lecture 17 – Functions (continued)

Lecture 6 – Operators in C (continued)