if else if ladder statement in C++ | ladder if statement in C++

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, TestCondition2, TestCondition3 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 TestCondition3 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.



Spread the love
Lesson tags: if else if ladder statement in C++language, ladder if statement in c, Program to demonstrate the use of if else if ladder statement in C++
Back to: C++ Programming Notes
Spread the love