Skip to main content

5.9) For Loops


A for loop in C++ is just 'syntactic sugar' for a while loop - i.e., a neater, more compact way of writing it:

for (int n = 10; n > 0; n--) {
  cout << n << '\n';
}
cout << "Lift-off!" << endl;

Key Points

  • The ( ) of the loop contains three elements, separated by semi-colons:
    • Initialization of the loop control variable
    • Testing of the variable to see whether loop body should execute
    • Modification of the variable
  • As with the while loop, { } are required around loop body if it contains multiple statements