Selection Statement
In a program a decision causes a one time jump to a different part of a program. Decisions in C++ are made in sever ways, most importantly with if ..else ... statement which chooses between two alternatives. Another decision statement ,switch creates branches for multiple alternatives sections of code, depending on the value of a single variable.
👉if statement
👉if-else statement
👉 Nested if statement
👉if-else-if ladder
If Statement
The if statement evaluates a condition, if the condition is true when a true-block (set of statements) is executed, otherwise the true-block is skipped.Syntax:
if ( expression )
true-block;
statement-x;
true-block;
statement-x;
If-Else Statement
In the above examples of if, you have seen that, a block of statements to true. What if there is another course of action to be followed if the condition evaluates to false. There is another form of if that allows for this kind of either or condition by providing an else clause. In if-else statement, first the expression or condition is evaluated to either true or false.
Syntax:
if ( expression )
{
True-block;
}
else
{
False-block;
}
Statement-x
Nested If
An if statement which contains another if statement is called nested if. The nested can have one of the following three forms.
Syntax:
if (expression-1)
{
// Executes when expression1 is true
if (condition2)
{
// Executes when expression2 is true
}
}
If-Else-If Ladder
The if-else ladder is a multi-path decision making statem6. In this type of statement " if" is followed by one or more else if statements and finally end with an else statement.
Syntax:
if(expression 1)
{
Statement-1
}
else
If (expression 2)
{
Statement-2
}
else
if(expression 3)
{
Statement-3
}
else
{
Statement-4
}