Computer Science, asked by TbiaSamishta, 10 months ago

Explain the use of else-if ladder statement with suitable example.

Answers

Answered by divyabeniwal
0

A common programming construct that is based upon nested ifs is the if-else-ifladder. It looks like this 

 

The conditional expressions are evaluated from the top downward. As soon as a true condition is found, the statement associated with it is executed, and the rest of the ladder is bypassed. If non of the conditions is true, then the final else statement will be executed. The final else often acts as a default condition; that is, if all other conditions tests fail, then the last else statement is performed. If there is no final else and all other conditions are false then no action will take place. 

Example 

// Demonstration of if-else-if ladder

#include <iostream.h> 

main ( ) 

int x; 

cout << "Enter an integer between 1 and 6"; 

cin >> x; 

if(x==1) cout<<"The number is one n"; 

else if(x==2)cout<<"The number is two n"; 

else if(x==3)cout<<"The number is three n";

else if(x==4)cout<<"The number is four n"; 

else if(x==5)cout<<"The number is five n"; 

else if(x==6)cout<<"The number is six n"; 

else cout <<"You didn't follow the rules"; 

return 0; 

Answered by Secondman
2

The if else-if ladder of statements is used for the alternation of the flow in the execution of the program.

If else-if is generally used when we have a lot of conditions and tasks to be done when any of those conditions is true.

Another similar conditional statement is the switch statement.

However, switch statement cannot be used to check for anything other than equality.

So in those cases, where we want to check for anything other than equality, in a large number of conditions, we use switch statement.

For Example :

if(n<10)

{

  printf(“Less than 10”);

}

else if(n>10&n<20)

{

  printf(“More  than 10 less than 20”);

}  

else if(n>20&n<30)

{

  printf(“More  than 20 less than 30”);

}

else if(n>30&n<40)

{

  printf(“More  than 30 less than 40”);

}

Similar questions