← C++ tutorial

C++

Loops

C++'s for loop follows the same three-part structure as Java and JavaScript: initializer, condition, update.

Example: summing with a for loop

#include <iostream>
using namespace std;

int main() {
    int total = 0;
    for (int i = 1; i <= 5; i++) {
        total += i;
    }
    cout << "Total: " << total << endl;
    return 0;
}
Total: 15

Same shape, same result as the Java and JavaScript versions of this exact example elsewhere in this tutorial — worth comparing them side by side if you're learning more than one language, since the differences that remain (semicolons, cout vs. print, header includes) are genuinely small once the core loop logic is already familiar.

Example
#include <iostream>
using namespace std;

int main() {
    int total = 0;
    for (int i = 1; i <= 5; i++) {
        total += i;
    }
    cout << "Total: " << total << endl;
    return 0;
}
Output
Total: 15