Lecture 11 – Decisions (Nested-if)



Nested-if

There are situations where you need to check a condition which is nested in another condition. For example we have sorted list of numbers from 1 to 100. We have divided it into four equal quadrants. i.e.

Quadrant No
Values From
Values To
1
1
25
2
26
50
3
51
75
4
76
100

 

In above scenario, if the value is greater than 50, then it would be greater than 70. If the value is not greater than 50 then it cannot be greater than 70.

The general syntax of nested-if is

Syntax

if (condition)

{

if(condition)

{

………

}

……..

}

Let’s implement it in code, so that we would be in a better position to understand the working of nested-if; for better functionality I’ve added else to it.

#include <stdio.h>

#include <conio.h>

void main()

{

int value;

clrscr();                                                                                                






Output

Please enter the value to be searched: 79

Congratulations! Value found in FOURTH Quadrant

 

printf(“\nPlease enter the value to be searched: ”);





scanf(“%d”, &value);

if(marks>=50)

{

if(value>75)

{

printf(“\nCongratulations! Value found in FOURTH Quadrant”);

}             

else

{

printf(“\nCongratulations! Value found in THIRD Quadrant”);







Output

Please enter the value to be searched: 55

Congratulations! Value found in THIRD Quadrant

 


}

else

{

if(value>25)

{







Output

Please enter the value to be searched: 40

Congratulations! Value found in SECOND Quadrant

 


printf(“\nCongratulations! Value found in SECOND Quadrant”);

}

else

{

printf(“\nCongratulations! Value found in FIRST Quadrant”);







Output

Please enter the value to be searched: 20

Congratulations! Value found in FIRST Quadrant

 


 


}

}

getch();

}

Example 21 - Use of Nested if-else structure

 


 

Comments

Popular posts from this blog

Lecture 17 – Functions (continued)

Lecture 6 – Operators in C (continued)

Lecture 10 – Decisions (if-else-if)