if else if ladder statement in C++ | ladder if statement in C++
It is a multi way decision making statement in which there are multiple conditions one after another. Depending upon these conditions, specific sets of statements are executed.
The syntax of if else if ladder statement is:
if(Test-Condition1)
{
Statement-Block-1;
}
else if(Test-Condition2)
{
Statement-Block-2;
}
else if (Test-Condition3)
{
Statement-Block-3;
}
:
:
else
{
Statement-Block-N;
}
Test-Condition1, Test–Condition2, Test–Condition3 are various conditions.
Initially Test-Condition1 is checked. If it is true, Statement-Block-1 of statements will get executed. If Test-Condition1 is false, Test-Condition2 is checked. If Test-Condition2 is true Statement-Block-2 of statements gets executed. If Test-Condition2 is false, Test-Condition3 will be checked. If Test–Condition3 is true Statement-Block-3 of statements gets executed.
Statement-Block-N Block-N will execute if all conditions are false.
Example:
include<iostream> using namespace std; int main() { int n; cout<<“Enter a number ="; cin>>n; if(n>0) cout<<“Number is positive"; else if(n<0) cout<<“Number is negative"; else cout<<“Number is zero"; return(0); }
Output
Enter a number =4 Number is positive
In the above program, variable n has been entered 4. Condition if(n>0) is true, so cout<<“Number is positive” gets executed.