You are currently viewing C++ Looping: Everything You Need to Know

C++ Looping: Everything You Need to Know

Looping is a fundamental concept in programming that allows us to repeat a block of code multiple times. In C++, there are several types of loops available, each serving a different purpose. This article explores the various looping constructs in C++, and provide practical examples along the way. Additionally, we will delve into loop control statements such as break and continue, which allow us to alter the flow of the loop execution.

The for Loop

The for loop is one of the most commonly used looping constructs in C++. It consists of an initialization, condition, and an increment/decrement expression. The loop executes until the condition becomes false.

Let’s see an example that prints numbers 1 through 10 using a for loop:

#include <iostream>

int main() {

    for (int i = 1; i <= 10; i++) {

        std::cout << i << " ";

    }
	
    return 0;
    
}

We initialize the variable i to 1. The loop continues as long as i is less than or equal to 10. After each iteration, i is incremented by 1. The loop prints the value of i using std::cout and a space. This process continues until i reaches 11, at which point the condition becomes false, and the loop terminates.

Let’s see an example that prints elements of an array using the for loop, and indexing:

#include <iostream>

int main() {

    int numbers[10]{
        1, 2, 3, 4, 5,
        6, 7, 8, 9, 10
    };

    for(int i = 0; i < 10; ++i) {

        // Print element at position i
        std::cout << numbers[i] << std::endl;

    }

    return 0;

}

We create an array named numbers that stores the integers from 1 to 10. Then, we use a for loop to iterate over the elements of the array. The loop starts with an initialization statement where we set the variable i to 0, which represents the index of the first element. The loop continues as long as i is less than 10, which ensures that we iterate through all the elements of the array. In each iteration, we print the value of the element at position i.

The while Loop

The while loop repeatedly executes a block of code as long as the specified condition remains true. Unlike the for loop, the initialization and increment/decrement statements are typically placed outside the loop.

Let’s see an example that prints numbers 1 through 10 using a while loop:

#include <iostream>

int main() {

    int i = 1;

    while (i <= 10) {

        // Print the value of i
        std::cout << i << " ";

        // Add 1 to i
        i++;
        
    }

    return 0;

}

We initialize the variable i to 1 before entering the loop. The loop executes as long as i is less than or equal to 10. Inside the loop, we print the value of i and then increment it by 1 using the i++ statement. The loop continues until i becomes 11, at which point the condition becomes false, and the loop terminates.

The do-while Loop

Similar to the while loop, the do-while loop executes a block of code repeatedly as long as the condition remains true. However, in this case, the condition is checked at the end of each iteration.

Let’s see an example that uses a do-while loop to repeatedly asks the user to enter a value until they enter “q” (case-insensitive):

#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>

std::string& lowercase(std::string& str);

int main() {

    // Holds the exit key entered by the user
    std::string exitKey;

    do {

        std::cout << "Enter 'q' to terminate program: " << std::endl;
        std::getline(std::cin, exitKey);

    } while(lowercase(exitKey) != "q");

    std::cout << "Exiting Program..." << std::endl;

    return 0;

}

std::string& lowercase(std::string& str) {

    std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) {
        return std::tolower(c);
    });

    return str;

}

The code demonstrates the usage of a do-while loop to repeatedly prompt the user for input until they enter the character “q”. The input is converted to lowercase using the lowercase function to ensure case insensitivity. The lowercase function is a user defined function, which takes a std::string& parameter str by reference. It uses std::transform and a lambda function to convert each character in str to lowercase. The function returns a reference to the modified str.

The for each Loop

The for each loop, also known as the range-based for loop, provides a concise way to iterate over elements in a container, such as an array or a vector.

#include <iostream>
#include <vector>

int main() {

    // Vector of integers
    std::vector<int> vnumbers{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    
    // Iterating over vector elements
    for (const int& number : vnumbers) {

        std::cout << number << " ";

    }

    // Move to next line
    std::cout << std::endl;
    
    // Array of integers
    int anumbers[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    // Iterating over array elements
    for (const int& number : anumbers) {

        std::cout << number << " ";

    }

    return 0;

}

We have a vector named vnumbers and an array named anumbers that store a sequence of integers. The for each loop iterates over each element of the vector and array, assigning it to the variable number in each iteration. The loop body, indicated by the curly braces {}, contains the code that is executed for each element. We simply output the value of number followed by a space using std::cout. The loop continues until all elements in the vector or array have been processed.

The for each loop provides a more convenient and readable way to iterate over containers, eliminating the need for managing indices explicitly. It automatically deduces the type of elements in the container and simplifies the iteration process.

Loop Control Statements

Loop control statements, such as break and continue, allow us to alter the flow of loop execution based on specific conditions.

The break Statement

The break statement is used to terminate the execution of a loop prematurely. It is typically used when a certain condition is met, and the remaining iterations are no longer required.

#include <iostream>

int main() {
    
    for (int i = 1; i <= 10; i++) {

        if (i == 7) {

            // 7 found, exit loop
            break;

        }

        std::cout << i << " ";

    }

    return 0;

}

We have a for loop that iterates from 1 to 10. Inside the loop, we have an if statement that checks if the value of i is equal to 7. If this condition evaluates to true, the break statement is executed, causing the loop to terminate immediately. As a result, only the numbers 1 through 6 are printed before the loop ends.

The continue Statement

The continue statement is used to skip the current iteration of a loop and move to the next iteration. It is often employed when we want to bypass certain iterations based on a specific condition.

#include <iostream>

int main() {

    for (int i = 1; i < 10; i++) {

        if (i == 2 || i == 3) {

            // Move to next iteration
            continue;

        }

        std::cout << i << " ";

    }

    return 0;

}

We have a for loop that iterates from 1 to 10. Inside the loop, we have an if statement that checks if the value of i is equal to 2 or 3. If this condition is true, the continue statement is executed, causing the loop to skip the remaining code in the current iteration and move to the next iteration. As a result, the numbers 2 and 3 are skipped.

Conclusion

We covered the basics of looping in C++. We explored the for, for each, while, and do-while loops, providing practical examples for each. Additionally, we learned about the break and continue statements, which allow us to alter the flow of loop execution. By understanding these looping constructs and control statements, you can effectively write code that performs repetitive tasks and handles different scenarios within loops.

Looping is a powerful technique that helps automate repetitive tasks and iterate over collections of data. Whether you need to process elements in an array, perform calculations, or handle input validation, mastering loop constructs in C++ is essential for efficient and concise programming.

Sources

I hope you found this information informative. If you would like to receive more content, please consider subscribing to our newsletter!

Leave a Reply