Navigating C++ Loops: Understanding Iteration over Containers

Topic Overview and Actualization

Greetings, Explorer! Today, we will delve into the essential tools of C++ loops. Loops in programming simplify and enhance the efficiency of repetitive tasks — much like a marathon of your favorite TV series. In this lesson, we will explore the universe of looping in C++ and gain hands-on experience by applying loops to Standard Template Library (STL) containers such as vectors and strings.

Understanding Looping

Imagine listening to your favorite song on repeat. That's the concept of loops in programming. For instance, we can use a for loop to print greetings for a group of friends.

C++
#include <iostream>
#include <vector>

int main() {
    std::vector<std::string> friends = {"Alice", "Bob", "Charlie", "Daniel"};
    for (const std::string& friend_name : friends) {
        // For each friend_name, prints the greeting
        std::cout << "Hello, " << friend_name << "! Nice to meet you.\n";
    }
    return 0;
}

Loops enable us to execute repetitive sequences automatically and efficiently.

For Loop in C++

The for loop is a control flow statement that allows code to be executed repeatedly. Here is how it generally works:

  1. Initialization: This is where you set up the loop variable. It's executed once when the loop begins.

  2. Condition: This Boolean expression determines if the loop will continue or stop. If it's true, the loop continues; if it's false, the loop ends and the flow jumps to the next statement after the loop.

  3. Iteration: This is where you update the loop variable. This statement executes after the loop body and right before the next condition check.

  4. Loop Body: The block of code to be executed in each loop.

The structure of a for loop is typically "for (initialization; condition; iteration) {loop body}", where the loop body gets executed for as long as the condition evaluates to true. After each loop, the iteration is executed which generally updates the value of the loop control variable.

Let's print a range of numbers using a for loop:

C++
#include <iostream>

int main() {
    for (int num = 0; num < 5; num++) {
        // This line prints numbers from 0 to 4
        std::cout << num << "\n";
    }
    return 0;
}

In each cycle of the loop, the variable (num) is updated before executing the code inside the block.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal