Saturday 4 April 2020

Nesting of if_else Statement in C++


When a series of decisions are involved in the statement, we may have to use more than one if_else statement in nested form. This can be described by the flowchart in the following figure:


Figure: Flow Chart of if_else statement in Nested Form

Example :
/ * finding the largest of 3 numbers * /
                main( )
                {
                            float a = 5, b = 2, c = 7;
                            if (a > b)
                            {
                                        if (a > c)
                                                    cout<<"a is greatest";
                                        else
                                                    cout<< "c is greatest";
                                            }
                                            else
                                            {
                                        if (b > c)
                                                cout<< "b is greatest";
                                        else
                                              cout<< "c is greatest";
                            }
                }
else if Ladder
There is another way of putting ifs together when multipath decisions are involved. Multipath decision is a chain of ifs in which statement associated with each else is an if.
It takes the following general form:

    if (condition 1)
                statement1;
    else if (condition 2)
                statement 2;
    else if (condition 3)
                statement 3;
    statement x;

The conditions in elseif ladder are evaluated from the top (of the ladder) downwards. As soon as the true condition is found, associated statement is executed and control is transferred to statement x.

No comments:

Post a Comment