Sage-Code Laboratory
index<--

C++ Control Flow

C++ is using C like control statements. These statements are based on structured programming theory. Are designed to avoid _spaghetti code_ that use to be created using goto statement. Two most important structures are conditionals and iterations.

Two-Ways Decision

This is the most common decision statement. It is based on logical expressions called condition. This can be as simple as a boolean variable or literal and also can be a complex expression that return a Boolean value: 0 = false or 1 = true. When condition is true one block is executed. When is false, the other block. This split the logic into two branches. After the decision was made, the program continue with next statement.

decision

Decision Diagram


Example:

#include <iostream>
using namespace std;
int main () {
    // Declaring local variable
    int num = 4;
    // check the boolean condition
    if (num > 4)
    {
        cout << "num is greater than 4" << endl;
    }
    cout << "Given number is : " << num << endl;
    return 0;
}

Notes:

Multi-Way Decision

In C++ we do not have elsif or elif like other languages but we have else keyword. This can be combined into a long decision chain or decision ladder. This is one of the most advanced selection statement that can be created in C++ but is also not very efficient.

decision

Ladder Diagram


Example:

#include <iostream>
using namespace std;
int main () {
    // declare local variable
    int marks = 55;

    // check the boolean condition
    if( marks >= 80 )
    {
        // 1st condition is true
        cout << "U are 1st class !!" << endl;
    }
    else if( marks >= 60 && marks < 80)
    {
        // 2nd condition is false
        cout << "U are 2nd class !!" << endl;
    }
    else if( marks >= 40 && marks < 60)
    {
        // 3rd condition is false
        cout << "U are 3rd class !!" << endl;
    }
    else
    {
        // none of condition is true
        cout << "U are fail !!" << endl;
    }
    return 0;
}

Switch Statement

This is a selection statement that is also multi-way decision like ladder statement. The difference is we use a selector variable. The selector can have different values or can be an expression that generate a value. In next example we have a selector variable "grade"; that can be: A, B, C, D,E, F. This is specific to US in schools we have these 6 levels of graduation used for exams. Observe this statement has a single block {....} each case can have one or several statements that are not enclosed in {...} up the the next case. Each case end with column ":" that is a punctuation symbol.

switch

Switch Diagram

Note:

Switch can be a little bit faster than chained if statement. A compiler can create an efficient "jump table" that will execute different parts of code (cases) depending on the selector values.


Example:

#include <iostream>
using namespace std;
int main () {
    // local variable declaration:
    char grade = 'C';
    switch(grade) {
        case 'A' :
            cout << "A grade" << endl;
            break;
        case 'B' :
            cout << "B grade" << endl;
            break;
        case 'C' :
            cout << "C grade" << endl;
            break;
        case 'D' :
            cout << "D grade" << endl;
            break;
        case 'F' :
            cout << "E grade" << endl;
            break;
    default :
        cout << "Invalid grade" << endl;
    }
    cout << "Your grade is " << grade << endl;
    return 0;
}

While Loop

The most common loop in any language is the while loop. This is used to repeat execution of statement block as long as a given condition is true. In C++ zero value of an expression is considered false and one or any number greater then 0 is considered true. This is also known as entry-controlled loop.

loop

Repetition Diagram


Syntax:

// while statement
while(<condition>) {
   //inside the repetitive block
   ...
}

Example:

Here is a simple while loop:

#include <iostream>
using namespace std;
int main ()
{
    // Local variable declaration
    int num = 5;
    // while loop execution
    while( num < 10 ) {
        cout << "Number : " << num << endl;
        num++;
    }
    return 0;
}

Do-While Loop

This loop is similar with while loop. The condition is at the end of the loop, therefore the loop is executed at least once. This is also called exit-controlled loop. Let's study the diagram below:

do-while

do-while diagram


Syntax:

do {
 ...
} while (condition);

Note: Fewer developers are using this kind of loop. Most of the time a while loop is good enough to resolve all the cases. This loop is also harder to read due the placement location of the conditional expression that is at the end.

Example:

#include <iostream>
using namespace std;
int main () {
    // Local variable declaration:
    int i = 0;
    // do loop execution
    do {
        cout << "value of i : " << i << endl;
        i++;
    } while( i < 10 );
    return 0;
}

For loop

The for loop is a little bit more complicated. This is created to repeat a block of code a predefined number of times. Usually this kind of loop is controller by a variable that is called control variable or index. The index is incremented each iteration with one. The final value will cause the loop to stop.

loop

For/Loop Repetition


Syntax:

for ( init; condition; increment ) {
    //inside the repetitive block
    ...
    if (condition) continue;
    ...
    if (condition) break;
    ...    
}

Example:

#include <iostream>
using namespace std;
int main () {
 // for loop execution
 for(int i = 0; i < 10; i = i + 1 ) {
    cout << "value of i : " << i << endl;
 }
 return 0;
}

Note: For efficient purpose increment can be (i++). That is a special feature of C++ to replace i=i+1. If you are familiar with Level language we do not think this is a big deal. We do not use ++ or — operators. Instead we use only i+=1 operator that is also efficient.

Early Termination

Any loop can be terminated before normal. For this we use "break"; keyword. Usually a break is controlled by the if statement. In next example we stop execution when count> 5.

#include <iostream>
using namespace std;
int main ()
{
    // Declaring Local variable
    int count = 0;
    // do loop execution
    do {
        cout << "Count : " << count << endl;
        count++;
        if (count > 5) {
            // Terminate the loop
            break;
        }
    } while( count < 20 );
    return 0;
}

Iteration Shortcut

Sometimes we can reach a point where the loop must continue with next iteration and skip the other statement before the loop end. This is called "shortcut"; or "continuation";. We use keyword "continue"; to continue the loop with next iteration.

#include <iostream>
using namespace std;
int main () {
    int count = 0;
    do {
        count++;
        if(count > 5 && count < 7)
        continue;
        cout << "Count : " << count << endl;
    } while( count < 10 );
    return 0;
}

Note: The loop control is manually alterred by using break or continue. Same two keywords can be used in all other repetitive statements (while, do-while). Using alterations can make the loops faster and easier to read.

GOTO Statement

This statement is restrictive in C++. This is the legacy statement from structured programming. It still exists in C++. It has to be used with caution. This is also called "unconditional jump"; statement.

Example:

label: statement;
 ...
goto label;

Example:

#include <iostream>
using namespace std;
int main ()
{
    int num = 1;
    here:do {
        if( num == 5) {
            num = num + 1;
            goto here;
        }
        cout << "value of num : " << num << endl;
        num = num + 1;
    } while (num < 10);
    return 0;
}

Notes:

  • Label can be backward or forward positioned in the code,
  • You can jump forward or backward depending on the position,
  • If you do not code exit condition properly, you may end-up with infinite loop.

  • Read next: Functions