C++-if-else-if-Ladder .

In this session i have discussed if-else-if ladder in C++ .


IF-Else-IF-Ladder :

It is also decision making and branching statement . If you have multiple choice then you can use the if-else-if ladder or switch . In if-else-if case first control check the if condition if it is true then the contorl come inside the if body other wise control transfer to else-if statement check the condition if it is true then contorl come inside the else if body and go on . If no any condition match then last else statement become execute .

IF-Elese-IF-statement-syntax :

 image


Example : Write a program check the days of week according to given value .

    #include<iostream>
    using namespace std; 
    int main()
    {
          int i=3;
          if(i==1)
          {
               cout<<"Sunday";
          }
          else if(i==2)
          {
               cout<<"Monday";
          }
          else if(i==3)
          {
               cout<<"Tuesday";
          }
          else if(i==4)
          {
               cout<<"Wednesday";
          }
          else if(i==5)
          {
               cout<<"Thursday";
          }
          else if(i==6)
          {
               cout<<"Friday";
          }
          else if(i==7)
          {
               cout<<"Sutarday";
          }
          else 
          {
               cout<<"Invalid Number";
          }
               cout<<"\nThanks";
          return 0;
    }
    
    OUTPUT : Tuesday
             Thanks
    


Example : Write a program that perform 1-Addition , 2-Subtraction , 3-multiplication , 4 Division .

    #include<iostream>
    using namespace std; 
    int main()
    { 
           int op=2;
           int x=20;
           int y=10;
           if(op==1)
           {
               int sum=x+y;
               cout<<"Sum= "<<sum;
           }
           else if(op==2)
           {
               int sub=x-y;
               cout<<"Sub= "<<sub;
           }
           else if(op==3)
           {
               int multi=x*y;
               cout<<"Multi= "<<multi;
           }
           else if(op==4)
           {
               int div=x/y;
               cout<<"Div= %d"<<div;
           }
           cout<<"\nThanks";
           return 0; 
    }
    
    OUTPUT : Sub= 10
             Thanks
    


Welcome to AndroidATPoint.

back image                     next image