Geek Slack

Learn C++
    About Lesson


    C++ For Loop


    C++ For Loop

    The for loop in C++ provides a concise way to execute a block of statements repeatedly. It is especially useful when you know the number of iterations beforehand or want to iterate over a range of values.

    1. Basic for Loop

    The basic syntax of the for loop:

    #include <iostream>
    
    int main() {
        for (int i = 1; i <= 5; ++i) {
            std::cout << "Iteration " << i << std::endl;
        }
    
        return 0;
    }

    2. Using for Loop with Arrays

    Example of iterating over an array using a for loop:

    #include <iostream>
    
    int main() {
        int numbers[] = {1, 2, 3, 4, 5};
    
        for (int i = 0; i < 5; ++i) {
            std::cout << "Number " << (i + 1) << ": " << numbers[i] << std::endl;
        }
    
        return 0;
    }

    3. Using for Loop with Iterators

    Example of iterating over a range using a for loop with iterators:

    #include <iostream>
    #include <vector>
    
    int main() {
        std::vector<int> numbers = {1, 2, 3, 4, 5};
    
        for (auto it = numbers.begin(); it != numbers.end(); ++it) {
            std::cout << "Number: " << *it << std::endl;
        }
    
        return 0;
    }

    4. Nested for Loops

    Example of nested for loops:

    #include <iostream>
    
    int main() {
        for (int i = 1; i <= 3; ++i) {
            for (int j = 1; j <= 3; ++j) {
                std::cout << "(" << i << ", " << j << ") ";
            }
            std::cout << std::endl;
        }
    
        return 0;
    }

    Conclusion

    The for loop in C++ is a powerful construct for iterating over a range of values or elements. This chapter covered its basic syntax, usage with arrays and iterators, and demonstrated nested for loops. Understanding how to effectively use for loops allows you to write efficient and concise code for repetitive tasks in your programs.