Flow of Control in C++ || if-else-else if in C++ || Learn about while, do-while, for and for-each (range based for) loops || Return statements || break and continue

 Control flow or Flow of Control in C++

by - Yashvardhan Singh

As you it was already discussed in previous blogs, C++ offers many statements to execute only a selected block of code, instead of blindly executing from top to bottom, today we are going to elaborate upon such statements.

The Control Flow statements can be divided under the following categories:

  • Decision making statements
  • Looping statements
  • Branching statements (Jump statements and return)
  • Others (async, coroutines, exceptions, etc.,) ...to be discussed later

Now let us discuss about the same:-

Decision making statements:-



If-else :

These C++ statements help you to make a decision, any command based upon 'if then' or 'if then else' logic can be written using if else statements.

Example:

#include <iostream>

int main()
{
    bool hungry = true;

    if (hungry)
    {
        std :: cout << "Give me something to eat" ;
    }

    else 
        std :: cout << "Stomach is full ! Going to sleep zzz..." ;
    return 0;
}

The above program illustrates a very basic day-to-day condition, if you are hungry, you ask for food, otherwise probably you take a nap :p

This is a control flow statement because depending upon whether or not you are hungry, it will print a message to output window, instead of blind execution of all the statements.

We can also make various choices using else if statement. Thereby making an if - else - else-if construct.

Example:

#include <iostream>

int main()
{
    int num = 27;

    if(num > 0)
        std :: cout << "Number is positive";
    else if (num == 0)
        std :: cout << "Number is zero";
    else
        std :: cout << "Number is negative";

   return 0;
}

Switch-case:

Just like the if else, switch case provides logic based decision. It compares the variable for various equalities (cases).

Example:

#include <iostream>

int main()
{
    bool hungry = true;

    char c = '7';

    switch(c)
    {
        case 48:    std :: cout << "The digit is = 0" ;
                    break;
        case 49:    std :: cout << "The digit is = 1" ;
                    break;
        case 50:    std :: cout << "The digit is = 2" ;
                    break;
        case 51:    std :: cout << "The digit is = 3" ;
                    break;
        case 52:    std :: cout << "The digit is = 4" ;
                    break;
        case 53:    std :: cout << "The digit is = 5" ;
                    break;
        case 54:    std :: cout << "The digit is = 6" ;
                    break;
        case 55:    std :: cout << "The digit is = 7" ;
                    break;
        case 56:    std :: cout << "The digit is = 8" ;
                    break;
        case 57:    std :: cout << "The digit is = 9" ;
                    break;
        default:    std :: cout << "The character is not a number" ;
    }

    return 0;
}

In the above piece of code with the switch case we have also discussed about jump statements which we are going to see further.


Looping statements:-



Loops help us executing a block of code repeatedly for some defined number of times, which if not defined properly can lead to a loop working for infinite iterations. 

The loop is also a control statement as it will execute its code, throw the control to its condition block, which if happens to be true, then again the loop body starts executing.

C++ provides the following loops: 

For Loop:

One of the most common and most used loops in most of the languages. It contains three parts, to initialize the loop/iterating variable to some value ; to check the condition for the loop to run ; and a part to update the loop variable for this iteration after which the condition is checked.

Syntax:

for (/*initialize iterating variable*/ ; /*condition*/ ; /*update*/)
    {
        /* code */
    }

Example:

#include <iostream>

int main()
{
    for (int i = 2i < 100i+=2)
    {
        std :: cout << i << " ";
    }
    /* the above code prints even numbers from 2 to 100 
        as the updation block updates the iterator by +2
        and iterator was initialized to 2*/

    return 0;
}


While Loop:

This loop lacks any kind of initializing and updation statements, due to which user has to do it by himself/manually.

syntax:

while (/* condition */)
    {
        /* code */
    }

Example:

#include <iostream>

int main()
{
    int i =2; // initializing our iterating variable manually
    while (i <= 100)
    {
        std :: cout << i << " " ; // main code

        i += 2 ; // updating manually in a while block
    }
    
    // the above code prints even numbers from 2 to 100

    return 0;
}

do-while loop:

All the other loops listed here were Entry-controlled, i.e., the condition of checked right after initializing the iterating variable or before running the code inside the body of the loop.

Do-while loop is slightly different as it is an Exit-controlled loop, which basically means the loop body executes first and then the condition is checked, therefore, no matter what the condition is a do-while loop will at least run once.

Just like its sibling (while loop), it too lacks a dedicated initializing or updation statement.

syntax:

do
    {
        /* code */
    } while (/* condition */);

Example:

#include <iostream>

int main()
{
    bool condition = false ;
    int i = 1;
    do
    {
        std :: cout << "Execution round : " << i++ << "\n";
    } while (condition);
    
    return 0;
}

Output:

Execution round : 1

This proves, even when the condition is false this loop executes its body once !


Range Based For loop:

Is a unique loop, which comes in very handy when you have to loop over data structures like array, String, vector, etc.

syntax:

    for (/*type*/ /*iterating variable*/ : /*ranged Variable*/)
    {
       /* code */
    }

Example:

#include <iostream>

int main()
{
    int wish[12] = {'N''A''M''A''S''T''E''W''O''R''L''D'};

    for (char c : wish)
        std :: cout << c << " ";    
    return 0;
}

Output:

N A M A S T E W O R L D 


Jump statements:-



The jump statements like break and continue are of much use within the other control flow statements like loops and switch case, to prevent execution of small piece of code while looping through various iterations.

Break:

Break statement is used to stop the execution of the loop (whether or not it is nested, only the loop containing break in its body is broken), or to prevent the fall-through (execution of  all the cases below the matching case)

Example:

#include <iostream>

int main()
{
    for (int row = 0 ; row < 5 ; row++){
        for(int col = 0 ; col < 5 ; col++){ 
            std :: cout << col ;
            if(col == 3break;
        }
        std :: cout << "\n";
    }
    // only the inner loop in which the break is written will break
    // print 0123
    //(5 times as row runs from 0 to 4, = 5 iterations)
    return 0;
}

Output:

    0123

    0123

    0123

    0123

    0123

Continue:

Unlike break, continue will not kill the loop entirely, in fact it will simply throw the control, to the updation/condition statement of the loop (basically skips any number of statements below it within the body of the loop)

Example:

#include <iostream>
using namespace std;

int main()
{
    for (int i = 1j = 0 ; i < 5j < 11 ; i++, j++)
    {
        if (i + j == 5)
        {
            j+=2;
            continue;
        }
        cout << i << " " << j << " " << (i+j<< "\n";
    }
    return 0;
}

Output:

    1 0 1

    2 1 3

    4 5 9

    5 6 11

    6 7 13

    7 8 15

    8 9 17

    9 10 19

Don't get confused from the above output. The ',' operator in initialization acts as to initialize and update both the variables. However, in a condition/logical statement ',' a comma will always yield the right hand side statement (i.e. the loop can be considered as: for (int i = 1, j = 0 ; j < 11 ; i++, j++)).

The below code and its output is a proof:

for (int i = 1j = 0 ; i < 11j < 7 ; i++, j++)
    {
        if (i + j == 5)
        {
            j+=2;
            continue;
        }
        cout << i << " " << j << " " << (i+j<< "\n";
    }

Output:

    1 0 1

    2 1 3

    4 5 9

    5 6 11

As you can see the output depends only on j and not on the value of i 


Return:-

Usually you will see it at the end of any function, however the position doesn't matter, a return statement is always found within a function.

It basically throws the control of execution of program back to the function or the block which triggered/called this function.

Example:

#include <iostream>
using namespace std;

void returnDemo()
{
    cout << "Inside the function\n";
    return;                          // now the control goes back to main()
    cout << "Leaving the function\n"; // skipped as the control is returned back
}

int main()
{
    cout << "let's call a function\n";
    cout << "Returned back to the main()\n";

    return 0;
}

Output:

let's call a function      

Returned back to the main()

Notice the line following return; was never executed as the control returned to the calling function before it could reach the following lines and execute them.

Therefore, any piece of code following return will not get executed unless the return itself was not executed (which can be achieved by placing it witching the if condition)


That's all for today, keep learning && keep coding ;

Thanks for reading :)

Comments

Popular posts from this blog

What Is Functions In C++ ? || Explained By Examples || Function Types

Basics Of Operators||Basics of operators in C++||Basics of operators in cpp||Types of operators in C++||Arithmetic Operators||Comparision Operators||Binary Operators||Logical Operators||Bitwise Operators||Assignment Operators||Miscellaneous Operators||Bitwise Explained||Operators Precedence||

Reference and Pointers in C++