Skip to the content of the web site.

Flow control

You have already learned conditional statements (or if statements) and looping statements (while-loops and for-loops) in Python. Right now, we will introduce a theorem:

The structured programming theorem
Any program that can be written can be written in a programming language that includes assignments, arithmetic and logical operators, and conditional statements and condition-controlled looping statements.

A condition-controlled looping statement is what is known in Python and C++ as a while-loop, and a for-loop is just a special case of a while-loop. Thus, while one language may be slower than another (Matlab is slower than Python, which is slower than Java, which is slower than C++), there is no no problem that Matlab cannot solve that C++ can.

The moral of this is that given any problem, if there is a solution to that problem, you can solve that problem using nothing more than if-statements and either while-loops or for-loops. Thus, if you train your thought processes to solve problems in terms of "I need do this while this condition is true..." and "I need do this if this condition is true..." then you will easily be able to translate your solutions into a C++ or Python or Java or Matlab program.

In this tutorial, we will describe:


Conditional statements

Like the if-statements of Python, C++ also uses similar statements:

     if some-condition:
         # Consequent block of statements to execute...

while in C++, this would appear as (with the parentheses being mandatory):

     if ( some-condition ) {
         // Consequent block of statements to execute...
     }

If you have an if-else statement in Python, it would look as follows:

     if some-condition:
         # Consequent block of statements to execute...
     else:
         # Alternative block of statements to execute...

In C++, you would have:

     if ( some-condition ) {
         // Consequent block of statements to execute...
     } else {
         // Alternative block of statements to execute...
     }

In Python, if you have cascading conditional statements, you may have:

     if first-condition:
         # First consequent block of statements to execute...
     elif second-condition:
         # Second consequent block of statements to execute...
     elif third-condition:
         # Third consequent block of statements to execute...
     else:
         # Complementary alternative block of statements to execute...

In C++, you would have:

     if ( first-condition ) {
         // First consequent block of statements to execute...
     } else if ( second-condition ) {
         // Second consequent block of statements to execute...
     } else if ( third-condition ) {
         // Third consequent block of statements to execute...
     } else {
         // Complementary alternative block of statements to execute...
     }

Thus, you now understand the structure of conditional statements. If you want to sound like a professional programmer, call these conditional statements, consequent blocks or bodies, and alternative blocks or bodies.


While loops

A while-loop in Python is similar to a simple conditional statement, only it uses the keyword while:

     while some-condition:
         # Body of statements to execute...

In C++, this would appear as (with the parentheses being mandatory):

     while ( some-condition ) {
         // Body of statements to execute...
     }

If you want to terminate the execution of a while-loop early, you can use a break; statement, just like in Python:

    while some-condition:
        # Start of body of statements to execute...
        if condition-to-terminate-loop:
            break
        # Balance of body block of statements to execute...

In C++, this would appear as:

     while ( some-condition ) {
        // Start of body of statements to execute...

        if ( condition-to-terminate-loop ) {
            break;
        }

        // Balance of body of statements to execute...
    }

Like Python, C++ also has a continue; statement that works in the same way.

If you want an infinite loop, in Python you would use

    while True:
        # Body of statements to execute...

In C++, this would appear as:

    while ( true ) {
        // Body of statements to execute...
    }

For loops

A for-loop in Python iterates through a sequence of objects, and this is similar to a for-loop in Matlab. Since the 2011 C++ standard (C++-11), C++ also has such a for-loop. When you look at the topic on the standard template library (STL), you will see such a for-loop. In Python, you may have

    for variable in Sequence:
        # Body of statements to execute...

In C++, the equivalent would be:

    for ( auto variable : container ) {
        // Body of statements to execute...
    }

The auto is a new keyword we haven't introduced yet. It is a statement to the compiler: "You determine the type of this variable." For example, if the container is a container of int, then the variable will be declared to be of type int.

The classic for-loop in C++ is actually just a while-loop in disguise. The original programmers of C recognized that very often, they were creating while loops of the form:

    typename variable{initial-value};

    while ( some-condition-usually-involving-variable ) {
        // Body of statements to execute...

        // Update to variable
        ++variable;         // As an example...
    }

This was sufficiently common that they introduced a for-loop of the form:

    for (
        typename variable{initial-value};
        some-condition-usually-involving-variable;
	++variable /* update to variable */
    ) {
        // Body of statements to execute...
    }

For example:

    for ( int k{0}; k < n; ++k ) {
        // Body of statements to execute...
    }

It is important to note that this may not simply iterate n times with n taking on the values 0, 1, 2, ..., n - 1, because the body itself may modify k. Thus, the above for-loop is identical to

    int k{0};
    while ( k < n ) {
        // Body of statements to execute...
        ++k;
    }

To give other examples of such code:

    // Here, k = 1, 2, 4, 8, 16, 32, ..., 1024
    for ( int k{1}; k < 2000; k *= 2 ) {
        // Body of statements to execute...
    }
    // Here, k = 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0
    for ( unsigned int k{10}; k <= 10; --k ) {
        // Body of statements to execute...
    }

With this last for-loop, when k == 0, because k is unsigned, --k produces the largest unsigned int, 4294967295, and so the condition fails.

In one case, I was copying the last few entries of one array onto the end of a second array, so my code looked like:

    for ( unsigned int m{13}, n{25}; m < M; ++m, ++n ) {
        second_array[n] = first_array[m];
    }

The beauty of the for-loop in C++ is that it succinctly informs the reader:

  • what must be initialized to execute the loop,
  • what the condition is to continue executing the loop, and
  • what must be done at the end of the execution of the loop.

Do-while-loops

One loop structure that Python does not have is a do-while-loop. This is just the same as a while-loop, except the condition is not checked until the first time the body is executed. The structure in C++ is:

     do {
        // Body of statements to execute...
     while ( some-condition );

This could be emulated in Python as follows:

     # Body of statements to execute...

     while some-condition:
        # Body of statements to execute...

This, however, leads to repetition of code, so instead you may have

     while some-condition:
        # Body of statements to execute...
        if some-condition:
            break;

A do-while-loop is useful if you require information from a sensor or other input prior to determining whether or not you should continue looping:

    int guess;

    do {
        std::cout << "Guess an integer: "
        std::cin >> guess;
    } while ( guess != 616 );