if-else-if Statement With Example || Nested if Statement With Example

 if-else-if Statement

The if...else... if statement can be used to choose one block of statements from many blocks of statements. It is used when there are many options and only one block of statements should be executed on the basis of a condition.

Syntax

The syntax of if-else-if statement is as follows:

if (condition)
{
block 1;
}
else if (condition)
{
block 2;
}
else if (condition)
{
block 3;
}
else
{
block N;
}

Working of if-else-if

The test conditions in if else if statement with multiple alternatives are executed in a sequence until a true condition is reached. If a condition is true, the block of statements following the condition is executed.

The remaining blocks are skipped If a condition is false the block of statements following the condition is skipped. The statement after the last else are executed if all conditions are false.

Nested if Statement

An if statement within an if statement is called nested if statement. In nested structure. the control enters into the inner if only when the outer condition is true. Only one block of statements are executed and the remaining blocks are skipped automatically.

The user can use as many if statements inside another if statement as required. The increase in the level of nesting increases the complexity of nested if statements.

Working of Nested IF

In nested if statement, the condition of outer if is evaluated first. If it is true, the control enters in the inner if block. If the condition is false, the inner if is skipped and control directly moves to the else part of outer if. 

If outer if is true then the control enters in the inner if statement. The inner if evaluated according to simple if statement.

How it Works?

The above program inputs three numbers and finds the smallest one. When the control enters the outer box, first condition if(a<b) is evaluated. If it is true, the controls enters in the smaller box and the condition if(a<c) is evaluated.

If it is also true, the value of a is displayed, otherwise the value of c is displayed. If the first condition if(a<b) is false, the control shifts to else part of if statement. Now the condition if(b<c) is evaluated. If it is true the value of b is displayed, otherwise the value of c is displayed.

Post a Comment

0 Comments