Loops syntax

loops are used to execute a block of code repeatedly as long as a specified condition is met. There are several types of loops in C++: for, while, do-while, and the range-based for loop. Here’s a detailed explanation of each:

for Loop

The for loop is used when the number of iterations is known beforehand. It consists of three parts: initialization, condition, and update. The syntax is:

for (initialization; condition; update) {
    // code to be executed
}
  • initialization: This step is executed once before the loop starts. It’s typically used to initialize the loop control variable.
  • condition: Before each iteration, the condition is evaluated. If it’s true, the loop body is executed; if it’s false, the loop terminates.
  • update: This step is executed after each iteration and is generally used to update the loop control variable.

Example:

for (int i = 0; i < 10; i++) {
    std::cout << "i: " << i << std::endl;
}

while Loop

The while loop is used when the number of iterations is not known and depends on a condition. The syntax is:

while (condition) {
    // code to be executed
}
  • condition: The loop continues to execute as long as this condition is true.

Example:

int i = 0;
while (i < 10) {
    std::cout << "i: " << i << std::endl;
    i++;
}

do-while Loop

The do-while loop is similar to the while loop, but it guarantees that the loop body is executed at least once. The syntax is:

do {
    // code to be executed
} while (condition);
  • condition: The loop continues to execute as long as this condition is true. The condition is evaluated after each iteration.

Example:

int i = 0;
do {
    std::cout << "i: " << i << std::endl;
    i++;
} while (i < 10);

Range-based for Loop (C++11 and later)

The range-based for loop is used to iterate over elements in a container (like arrays, vectors, etc.). It simplifies the syntax and enhances readability. The syntax is:

for (type variable : container) {
    // code to be executed
}

Example:

int arr[] = {1, 2, 3, 4, 5};
for (int num : arr) {
    std::cout << "num: " << num << std::endl;
}

Nested Loops

Loops can be nested inside other loops. Each loop will run its full course for every iteration of the outer loop.

Example:

for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) {
        std::cout << "i: " << i << ", j: " << j << std::endl;
    }
}

Loop Control Statements

break: Terminates the loop and transfers control to the statement immediately following the loop.

for (int i = 0; i < 10; i++) {
    if (i == 5) {
        break;
    }
    std::cout << "i: " << i << std::endl;
}

continue: Skips the current iteration of the loop and proceeds with the next iteration.

for (int i = 0; i < 10; i++) {
    if (i % 2 == 0) {
        continue;
    }
    std::cout << "i: " << i << std::endl;
}