Control Flow Structures in C++

C++C++Beginner
Practice Now

Introduction

In this lab, you will learn how to implement various control flow structures in C++, including single and multi-branch if-else statements, switch statements, counter-controlled for loops, entry-controlled while loops, exit-controlled do-while loops, and nested loops. You will also explore the use of the break and continue statements to control loop execution. These fundamental programming constructs are essential for building more complex and dynamic applications in C++.

The lab covers a range of topics, from writing conditional statements to creating loops with different execution logics. By the end of this lab, you will have a solid understanding of how to use these control flow structures to make your C++ programs more flexible and adaptable to different scenarios.

Write Single and Multi-branch if-else Statements

In this step, you'll learn how to write single and multi-branch if-else statements in C++. Conditional statements allow your program to make decisions and execute different code blocks based on specific conditions.

First, navigate to the project directory and create a new C++ file for this lab:

cd ~/project
touch conditional_statements.cpp

Open the conditional_statements.cpp file in the WebIDE and add the following code to explore single and multi-branch if-else statements:

#include <iostream>

int main() {
    // Single if statement
    int number = 10;
    if (number > 5) {
        std::cout << "Number is greater than 5" << std::endl;
    }

    // if-else statement
    int age = 20;
    if (age >= 18) {
        std::cout << "You are an adult" << std::endl;
    } else {
        std::cout << "You are a minor" << std::endl;
    }

    // Multi-branch if-else statement
    int score = 75;
    if (score >= 90) {
        std::cout << "Grade: A" << std::endl;
    } else if (score >= 80) {
        std::cout << "Grade: B" << std::endl;
    } else if (score >= 70) {
        std::cout << "Grade: C" << std::endl;
    } else if (score >= 60) {
        std::cout << "Grade: D" << std::endl;
    } else {
        std::cout << "Grade: F" << std::endl;
    }

    return 0;
}

Compile and run the program:

g++ conditional_statements.cpp -o conditional_statements
./conditional_statements

Example output:

Number is greater than 5
You are an adult
Grade: C

Let's break down the different types of if-else statements:

  1. Single if statement:

    • Executes a block of code if the condition is true
    • No alternative action if the condition is false
  2. if-else statement:

    • Provides two paths of execution
    • Executes one block if the condition is true
    • Executes another block if the condition is false
  3. Multi-branch if-else statement:

    • Allows multiple conditions to be checked
    • Uses else if to add more conditions
    • The else block serves as a default case

Key points about if-else statements:

  • Conditions are evaluated from top to bottom
  • Only one block of code will be executed
  • Use curly braces { } to define code blocks
  • Comparison operators like >, >=, <, <=, ==, != are used in conditions

Create switch Statement with Multiple case Labels

In this step, you'll learn how to use the switch statement in C++ to handle multiple conditions based on a single variable. The switch statement provides an alternative to multiple if-else statements when comparing a variable against different constant values.

First, navigate to the project directory and create a new C++ file:

cd ~/project
touch switch_statement.cpp

Open the switch_statement.cpp file in the WebIDE and add the following code to explore switch statements:

#include <iostream>

int main() {
    // Basic switch statement with multiple case labels
    int dayNumber = 3;

    switch (dayNumber) {
        case 1:
            std::cout << "Monday" << std::endl;
            break;
        case 2:
            std::cout << "Tuesday" << std::endl;
            break;
        case 3:
            std::cout << "Wednesday" << std::endl;
            break;
        case 4:
            std::cout << "Thursday" << std::endl;
            break;
        case 5:
            std::cout << "Friday" << std::endl;
            break;
        case 6:
            std::cout << "Saturday" << std::endl;
            break;
        case 7:
            std::cout << "Sunday" << std::endl;
            break;
        default:
            std::cout << "Invalid day number" << std::endl;
    }

    // Switch statement with multiple cases sharing the same code block
    char grade = 'B';

    switch (grade) {
        case 'A':
        case 'B':
            std::cout << "Excellent performance!" << std::endl;
            break;
        case 'C':
        case 'D':
            std::cout << "Good performance" << std::endl;
            break;
        case 'F':
            std::cout << "Need improvement" << std::endl;
            break;
        default:
            std::cout << "Invalid grade" << std::endl;
    }

    return 0;
}

Compile and run the program:

g++ switch_statement.cpp -o switch_statement
./switch_statement

Example output:

Wednesday
Excellent performance!

Key points about switch statements:

  1. Used to select one of many code blocks to execute
  2. Works with integral types (int, char, enum)
  3. Each case represents a possible value
  4. break statement prevents fall-through to next case
  5. default case handles values not matched by other cases
  6. Multiple cases can share the same code block

Important switch statement rules:

  • Each case must end with a break or return
  • Cases must be constant expressions
  • Only one block of code will be executed
  • default case is optional but recommended

Initialize Counter-controlled for Loops

In this step, you'll learn how to use counter-controlled for loops in C++. for loops are essential for executing a block of code a specific number of times, making them perfect for tasks that require repetition with a known number of iterations.

First, navigate to the project directory and create a new C++ file:

cd ~/project
touch for_loops.cpp

Open the for_loops.cpp file in the WebIDE and add the following code to explore different ways of initializing and using for loops:

#include <iostream>

int main() {
    // Basic counter-controlled for loop
    std::cout << "Counting from 1 to 5:" << std::endl;
    for (int i = 1; i <= 5; i++) {
        std::cout << i << " ";
    }
    std::cout << std::endl;

    // For loop with multiple statements in initialization
    std::cout << "Counting even numbers from 0 to 10:" << std::endl;
    for (int j = 0, k = 10; j <= k; j += 2) {
        std::cout << j << " ";
    }
    std::cout << std::endl;

    // For loop with multiplication table
    std::cout << "Multiplication table for 5:" << std::endl;
    for (int m = 1; m <= 10; m++) {
        std::cout << "5 x " << m << " = " << (5 * m) << std::endl;
    }

    return 0;
}

Compile and run the program:

g++ for_loops.cpp -o for_loops
./for_loops

Example output:

Counting from 1 to 5:
1 2 3 4 5
Counting even numbers from 0 to 10:
0 2 4 6 8 10
Multiplication table for 5:
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

Key components of a for loop:

  1. Initialization: int i = 1 - Sets the initial value of the counter
  2. Condition: i <= 5 - Defines when the loop should continue
  3. Increment/Decrement: i++ - Changes the counter after each iteration

Important for loop characteristics:

  • Ideal for known number of iterations
  • Can have multiple initialization statements
  • Can modify multiple variables in each iteration
  • Flexible in controlling loop execution

Create while Loops with Entry-controlled Logic

In this step, you'll learn how to use while loops in C++. A while loop is an entry-controlled loop that repeatedly executes a block of code as long as a specified condition remains true. The condition is checked before each iteration, which means the loop might not execute at all if the initial condition is false.

First, navigate to the project directory and create a new C++ file:

cd ~/project
touch while_loops.cpp

Open the while_loops.cpp file in the WebIDE and add the following code to explore different ways of using while loops:

#include <iostream>

int main() {
    // Basic while loop counting
    std::cout << "Counting from 1 to 5:" << std::endl;
    int count = 1;
    while (count <= 5) {
        std::cout << count << " ";
        count++;
    }
    std::cout << std::endl;

    // While loop with user input validation
    int userNumber;
    std::cout << "Enter a number between 1 and 10: ";
    std::cin >> userNumber;

    while (userNumber < 1 || userNumber > 10) {
        std::cout << "Invalid input. Enter a number between 1 and 10: ";
        std::cin >> userNumber;
    }
    std::cout << "You entered a valid number: " << userNumber << std::endl;

    // While loop calculating factorial
    int number = 5;
    int factorial = 1;
    int i = 1;

    std::cout << "Calculating factorial of " << number << ":" << std::endl;
    while (i <= number) {
        factorial *= i;
        i++;
    }
    std::cout << number << "! = " << factorial << std::endl;

    return 0;
}

Compile and run the program:

g++ while_loops.cpp -o while_loops
./while_loops

Example output:

Counting from 1 to 5:
1 2 3 4 5
Enter a number between 1 and 10: 15
Invalid input. Enter a number between 1 and 10: 7
You entered a valid number: 7
Calculating factorial of 5:
5! = 120

Key characteristics of while loops:

  1. Condition is checked before each iteration
  2. Loop may not execute if initial condition is false
  3. Requires manual increment/update of loop variable
  4. Useful for situations where the number of iterations is not known beforehand

Important while loop components:

  • Initialization of loop variable before the loop
  • Condition that controls loop execution
  • Update of loop variable inside the loop body

Implement do-while Loops for Exit-controlled Logic

In this step, you'll learn about do-while loops in C++. Unlike while loops, do-while loops are exit-controlled, which means the condition is checked after executing the loop body. This ensures that the loop body is executed at least once, regardless of the initial condition.

First, navigate to the project directory and create a new C++ file:

cd ~/project
touch do_while_loops.cpp

Open the do_while_loops.cpp file in the WebIDE and add the following code to explore different ways of using do-while loops:

#include <iostream>
#include <cstdlib>
#include <ctime>

int main() {
    // Basic do-while loop for user input validation
    int userNumber;
    do {
        std::cout << "Enter a number between 1 and 10: ";
        std::cin >> userNumber;
    } while (userNumber < 1 || userNumber > 10);
    std::cout << "You entered a valid number: " << userNumber << std::endl;

    // Simulating a dice rolling game
    srand(time(0));  // Seed for random number generation
    int attempts = 0;
    int targetNumber = 6;
    int diceRoll;

    std::cout << "Dice Rolling Game:" << std::endl;
    do {
        diceRoll = rand() % 6 + 1;  // Generate random number between 1 and 6
        attempts++;
        std::cout << "Roll " << attempts << ": You rolled " << diceRoll << std::endl;
    } while (diceRoll != targetNumber);

    std::cout << "Congratulations! You rolled the target number "
              << targetNumber << " in " << attempts << " attempts." << std::endl;

    return 0;
}

Compile and run the program:

g++ do_while_loops.cpp -o do_while_loops
./do_while_loops

Example output:

Enter a number between 1 and 10: 15
Enter a number between 1 and 10: 7
You entered a valid number: 7
Dice Rolling Game:
Roll 1: You rolled 1
Roll 2: You rolled 5
Roll 3: You rolled 2
Roll 4: You rolled 5
Roll 5: You rolled 5
Roll 6: You rolled 3
Roll 7: You rolled 4
Roll 8: You rolled 2
Roll 9: You rolled 2
Roll 10: You rolled 2
Roll 11: You rolled 2
Roll 12: You rolled 2
Roll 13: You rolled 1
Roll 14: You rolled 1
Roll 15: You rolled 6
Congratulations! You rolled the target number 6 in 15 attempts.

Key characteristics of do-while loops:

  1. Condition is checked after executing the loop body
  2. Guarantees at least one execution of the loop
  3. Useful for input validation and games
  4. Syntax differs from while loop by checking condition at the end

Important do-while loop components:

  • do keyword starts the loop body
  • Loop body is always executed at least once
  • while condition is evaluated after each iteration
  • Semicolon ; is required after the while condition

Use break to Exit Loops Early

In this step, you'll learn how to use the break statement to exit loops prematurely in C++. The break statement allows you to immediately terminate a loop and transfer control to the first statement after the loop.

First, navigate to the project directory and create a new C++ file:

cd ~/project
touch break_statement.cpp

Open the break_statement.cpp file in the WebIDE and add the following code to explore different ways of using the break statement:

#include <iostream>
#include <cstdlib>
#include <ctime>

int main() {
    // Breaking out of a for loop when a condition is met
    std::cout << "Finding the first even number:" << std::endl;
    for (int i = 1; i <= 10; i++) {
        if (i % 2 == 0) {
            std::cout << "First even number found: " << i << std::endl;
            break;
        }
    }

    // Simulating a number guessing game
    srand(time(0));  // Seed for random number generation
    int targetNumber = rand() % 10 + 1;  // Random number between 1 and 10
    int guess;
    int attempts = 0;

    std::cout << "\nNumber Guessing Game:" << std::endl;
    while (true) {
        std::cout << "Enter your guess (1-10): ";
        std::cin >> guess;
        attempts++;

        if (guess == targetNumber) {
            std::cout << "Congratulations! You guessed the number in "
                      << attempts << " attempts." << std::endl;
            break;
        } else if (guess < targetNumber) {
            std::cout << "Too low. Try again." << std::endl;
        } else {
            std::cout << "Too high. Try again." << std::endl;
        }
    }

    return 0;
}

Compile and run the program:

g++ break_statement.cpp -o break_statement
./break_statement

Example output:

Finding the first even number:
First even number found: 2

Number Guessing Game:
Enter your guess (1-10): 5
Too low. Try again.
Enter your guess (1-10): 8
Too high. Try again.
Enter your guess (1-10): 6
Congratulations! You guessed the number in 3 attempts.

Key characteristics of the break statement:

  1. Immediately terminates the innermost loop
  2. Transfers control to the first statement after the loop
  3. Can be used in for, while, and do-while loops
  4. Useful for early loop termination based on a condition

Important break statement uses:

  • Exiting loops when a specific condition is met
  • Implementing search algorithms
  • Creating interactive programs with user input
  • Preventing unnecessary iterations

Skip Loop Iterations with continue Statement

In this step, you'll learn how to use the continue statement in C++ to skip the current iteration of a loop and move to the next iteration. The continue statement allows you to selectively skip parts of a loop based on specific conditions.

First, navigate to the project directory and create a new C++ file:

cd ~/project
touch continue_statement.cpp

Open the continue_statement.cpp file in the WebIDE and add the following code to explore different ways of using the continue statement:

#include <iostream>

int main() {
    // Skipping even numbers in a loop
    std::cout << "Printing odd numbers between 1 and 10:" << std::endl;
    for (int i = 1; i <= 10; i++) {
        if (i % 2 == 0) {
            continue;  // Skip even numbers
        }
        std::cout << i << " ";
    }
    std::cout << std::endl;

    // Filtering out negative numbers in a sum calculation
    int sum = 0;
    int numbers[] = {5, -3, 10, -7, 8, -2, 15};
    int arraySize = sizeof(numbers) / sizeof(numbers[0]);

    std::cout << "\nCalculating sum of positive numbers:" << std::endl;
    for (int j = 0; j < arraySize; j++) {
        if (numbers[j] < 0) {
            continue;  // Skip negative numbers
        }
        sum += numbers[j];
        std::cout << "Added: " << numbers[j] << ", Current Sum: " << sum << std::endl;
    }
    std::cout << "Final Sum of Positive Numbers: " << sum << std::endl;

    return 0;
}

Compile and run the program:

g++ continue_statement.cpp -o continue_statement
./continue_statement

Example output:

Printing odd numbers between 1 and 10:
1 3 5 7 9

Calculating sum of positive numbers:
Added: 5, Current Sum: 5
Added: 10, Current Sum: 15
Added: 8, Current Sum: 23
Added: 15, Current Sum: 38
Final Sum of Positive Numbers: 38

Key characteristics of the continue statement:

  1. Skips the rest of the current loop iteration
  2. Transfers control to the next iteration of the loop
  3. Can be used in for, while, and do-while loops
  4. Useful for filtering or conditional processing

Important continue statement uses:

  • Skipping specific iterations based on conditions
  • Filtering data in loops
  • Avoiding unnecessary computations
  • Simplifying loop logic

Create Nested Loops for Matrix Operations

In this step, you'll learn how to use nested loops to perform operations on 2D arrays (matrices) in C++. Nested loops allow you to iterate through rows and columns of a matrix, enabling complex data manipulation and calculations.

First, navigate to the project directory and create a new C++ file:

cd ~/project
touch nested_loops.cpp

Open the nested_loops.cpp file in the WebIDE and add the following code to explore matrix operations using nested loops:

#include <iostream>
#include <iomanip>

int main() {
    // Define a 3x3 matrix
    int matrix[3][3] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };

    // Print the original matrix
    std::cout << "Original Matrix:" << std::endl;
    for (int row = 0; row < 3; row++) {
        for (int col = 0; col < 3; col++) {
            std::cout << std::setw(4) << matrix[row][col];
        }
        std::cout << std::endl;
    }

    // Calculate row sums
    std::cout << "\nRow Sums:" << std::endl;
    for (int row = 0; row < 3; row++) {
        int rowSum = 0;
        for (int col = 0; col < 3; col++) {
            rowSum += matrix[row][col];
        }
        std::cout << "Row " << row + 1 << " Sum: " << rowSum << std::endl;
    }

    // Create and print a multiplication table
    std::cout << "\nMultiplication Table:" << std::endl;
    for (int i = 1; i <= 5; i++) {
        for (int j = 1; j <= 5; j++) {
            std::cout << std::setw(4) << (i * j);
        }
        std::cout << std::endl;
    }

    return 0;
}

Compile and run the program:

g++ nested_loops.cpp -o nested_loops
./nested_loops

Example output:

Original Matrix:
   1   2   3
   4   5   6
   7   8   9

Row Sums:
Row 1 Sum: 6
Row 2 Sum: 15
Row 3 Sum: 24

Multiplication Table:
   1   2   3   4   5
   2   4   6   8  10
   3   6   9  12  15
   4   8  12  16  20
   5  10  15  20  25

Key characteristics of nested loops:

  1. An inner loop completes all its iterations for each iteration of the outer loop
  2. Useful for working with multi-dimensional arrays
  3. Can be used to create complex patterns and perform matrix operations
  4. Typically used with 2D arrays (matrices) and multi-dimensional data structures

Important nested loop concepts:

  • Outer loop controls the number of times inner loop is executed
  • Each loop has its own counter variable
  • Useful for row and column-based operations
  • Can be used to generate patterns, perform calculations, and manipulate data

Handle Infinite Loop Prevention

In this step, you'll learn how to prevent infinite loops in C++ by implementing proper loop control mechanisms. An infinite loop occurs when a loop's condition never becomes false, causing the program to run indefinitely.

First, navigate to the project directory and create a new C++ file:

cd ~/project
touch infinite_loop_prevention.cpp

Open the infinite_loop_prevention.cpp file in the WebIDE and add the following code to explore different strategies for preventing infinite loops:

#include <iostream>
#include <cstdlib>
#include <ctime>

int main() {
    // Example 1: Preventing infinite loop with a maximum iteration limit
    std::cout << "Example 1: Iteration Limit Prevention" << std::endl;
    int counter = 0;
    const int MAX_ITERATIONS = 5;

    while (true) {
        std::cout << "Iteration: " << counter + 1 << std::endl;
        counter++;

        if (counter >= MAX_ITERATIONS) {
            std::cout << "Maximum iterations reached. Breaking the loop." << std::endl;
            break;
        }
    }

    // Example 2: User-controlled loop with input validation
    std::cout << "\nExample 2: User-Controlled Loop" << std::endl;
    char continueChoice;
    int attempts = 0;
    const int MAX_ATTEMPTS = 3;

    do {
        std::cout << "Enter a number (1-10): ";
        int userNumber;
        std::cin >> userNumber;

        if (userNumber >= 1 && userNumber <= 10) {
            std::cout << "Valid number entered: " << userNumber << std::endl;
            break;
        }

        attempts++;
        std::cout << "Invalid input. Attempts left: " << MAX_ATTEMPTS - attempts << std::endl;

        if (attempts >= MAX_ATTEMPTS) {
            std::cout << "Maximum attempts reached. Exiting." << std::endl;
            break;
        }

        std::cout << "Do you want to try again? (y/n): ";
        std::cin >> continueChoice;
    } while (continueChoice == 'y' || continueChoice == 'Y');

    // Example 3: Random number game with controlled iterations
    std::cout << "\nExample 3: Random Number Game" << std::endl;
    srand(time(0));  // Seed for random number generation
    int targetNumber = rand() % 10 + 1;
    int guess;
    int gameAttempts = 0;
    const int MAX_GAME_ATTEMPTS = 4;

    std::cout << "Guess the number between 1 and 10" << std::endl;
    while (gameAttempts < MAX_GAME_ATTEMPTS) {
        std::cout << "Attempt " << gameAttempts + 1 << ": Enter your guess: ";
        std::cin >> guess;

        if (guess == targetNumber) {
            std::cout << "Congratulations! You guessed the number." << std::endl;
            break;
        }

        gameAttempts++;

        if (gameAttempts >= MAX_GAME_ATTEMPTS) {
            std::cout << "Sorry, you've run out of attempts. The number was "
                      << targetNumber << std::endl;
            break;
        }
    }

    return 0;
}

Compile and run the program:

g++ infinite_loop_prevention.cpp -o infinite_loop_prevention
./infinite_loop_prevention

Example output:

Example 1: Iteration Limit Prevention
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5
Maximum iterations reached. Breaking the loop.

Example 2: User-Controlled Loop
Enter a number (1-10): 1
Valid number entered: 1

Example 3: Random Number Game
Guess the number between 1 and 10
Attempt 1: Enter your guess: 2
Attempt 2: Enter your guess: 3
Attempt 3: Enter your guess: 4
Attempt 4: Enter your guess: 5
Sorry, you've run out of attempts. The number was 8

Key strategies for preventing infinite loops:

  1. Set a maximum iteration limit
  2. Use break statement to exit loops
  3. Implement input validation
  4. Add conditional checks to control loop execution
  5. Provide user control mechanisms

Important infinite loop prevention techniques:

  • Always ensure the loop condition can become false
  • Use counter variables to limit iterations
  • Implement exit conditions within the loop
  • Validate user input
  • Use break to exit loops when needed

Summary

In this lab, you learned how to implement various control flow structures in C++, including single and multi-branch if-else statements, switch statements, counter-controlled for loops, entry-controlled while loops, exit-controlled do-while loops, and nested loops. You explored the use of break and continue statements to control loop execution, and learned techniques to handle infinite loops. These control flow structures are fundamental in C++ programming, allowing you to write more complex and dynamic programs that can make decisions and execute different code paths based on specific conditions.

The lab covered the practical application of these control flow structures through hands-on coding exercises, enabling you to develop a deeper understanding of their usage and the ability to apply them effectively in your own C++ projects.