C++ For Loop

The for loop in C++ is used to execute a block of code a fixed number of times. It is ideal when the number of iterations is known beforehand.

1. Basic For Loop Example

This example prints numbers from 1 to 5 using a for loop.

C++
Example: Basic for loop
#include <iostream>
using namespace std;

int main() {
    for(int i = 1; i <= 5; i++) {
        cout << i << endl;
    }
    return 0;
}

2. Common Mistakes

Common mistakes include incorrect loop boundaries or forgetting to update the loop variable, which may cause infinite loops or skipped iterations.

C++
Incorrect for loop example
#include <iostream>
using namespace std;

int main() {
    for(int i = 1; i <= 5;) { // Missing i++ increment
        cout << i << endl;
    }
    return 0;
}

Conclusion

C++ for loops are ideal for repeated execution when the number of iterations is known. Correct initialization, condition, and increment ensure smooth execution.