Published by: Nuru
Published date: 21 Jun 2021
IF-Else Statement is a bi-directional conditional control statement and an extension of the simple if statement we use regularly. It is used when there are possible actions. One when the condition is true and the other when the condition is false. If the condition is true then there is the execution of a single statement or a block of statements. That is one part of the program. Otherwise, there is the execution of another single statement or a block of statements. That is another part of the program.
Thus, the general form of the if-else statement is,
If (test expression is true)
{
True-block statement (s);
}
Else
{
False-block statement (s);
}
Statement-x;
For single line
If (condition)
Statement 1;
Else
Statement 2;
For Multiple line
If (condition)
{
Statement;
…………………… ;
}
Else
If the expression evaluates to true, there is the execution of the true block statements. If the expression evaluates to false, there is the execution of a false block statement.
A flowchart explains this in a better way. Thus, the flowchart of the if-else statement is below.
Using an if-else statement, we can specify an action to be performed both when the condition is true, and when it is false.
For Example, Let us see a program below.
If we declare another if-else statement in the block of if or the else block. These are known as nesting if-else statements. There is the execution of conditions from the top to bottom checking each condition. It checks whether it meets the conditional criteria or not. If it is found that, the condition is true then, it executes the block of an associated statement of a true part. Else, it goes to the next condition to execute.
Thus, the syntax is:
If (condition)
{
If (condition)
Statement;
Else
Statement;
}
Else
{
If (condition)
Statement;
Else
Statement;
}
The flowchart for the nested 'if statement' is :