← 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
Ready to go further?

These free tutorials are a preview of what a Code Secure Academy cohort covers, project work and all.

Explore our tracks
Don't miss out

Ready to build something real?

Create a free account to enroll in a track, and get notified the moment a cohort opens.

Create free account