Nested if / if-else statements
Sometimes we require to execute a set of statements based on the TRUEness or FALSEness of two or more conditions. In such a situation we can use nested if-statement or nested if-else statements.
Syntax- There can be infinite number of syntax for nested if-statement and nested if-else statements.
Syntax-1 |
Syntax-2 |
if
( condition) { if (condition) { Statement(s); } } |
if
( condition) { if (condition) { if (condition) { Statement(s); } } } |
Syntax-3 |
Syntax-4 |
if
( condition) { if (condition) { if (condition) { And so on… } } } |
if
( condition) { Statement(s); } else { if(condition) { Statement(s); } } |
Syntax-5 |
Syntax-6 |
if
( condition) { if(condition) { Statement(s); } } else { Statement(s); }
|
if
( condition) { if(condition) { Statement-1(s); } else { Statement-2(s); } } else { Statement-3(s); }
|
Syntax-7 |
Syntax-8 |
if
( condition) { Statement-3(s); } else { if(condition) { Statement-1(s); } else { Statement-2(s); } }
|
if
( condition-1) { if(condition-2) { Statement-1(s); } else { Statement-2(s); } } else { if(condition-3) { Statement-3(s); } else { Statement-4(s); } } |
Example-1
Marks of 5 subjects are input through the keyboard. Write a Program in C to print the total marks, percentage and division.
/* Program to display total marks, percentage and division [division.c] */
#include < stdio.h >
#include < conio.h >
void main ( )
{
// Variable Declaration
int s1, s2, s3, s4, s5, total ;
float per ;
clrscr ( );
// Input
printf ( “ \n Enter the marks of Physics \n “ );
scanf ( “ %d “, &s1 );
printf ( “ \n Enter the marks of Chemistry \n “ );
scanf ( “ %d “, &s2 );
printf ( “ \n Enter the marks of Maths \n “ );
scanf ( “ %d “, &s3 );
printf ( “ \n Enter the marks of English \n “ );
scanf ( “ %d “, &s4 );
printf ( “ \n Enter the marks of Computer Science \n “ );
scanf ( “ %d “, &s5 );
// Processing and Output
total = s1 + s2 + s3 + s4 +s5 ;
per = total / 5.0 ;
printf ( “ \n Total Marks = %d“, total );
printf ( “ \n Percentage = %f “, per );
if ( per > = 75 )
{
printf ( “ \n Distinction \n “ );
}
if ( per > = 60 )
{
if ( per < 75)
printf ( “ \n First Division \n “ );
}
if ( per > = 45 )
{
if ( per < 60)
printf ( “ \n Second Division \n “ );
}
if ( per > = 33 )
{
if ( per < 45)
printf ( “ \n Third Division \n “ );
}
if ( per < 33 )
{
printf ( “ \n Fail \n “ );
}
getch ( );
}