1.4.2. The for Statement
In our while loop we used the variable val to control how many times we executed the loop. We tested the value of val in the condition and incremented val in the while body.
This pattern—using a variable in a condition and incrementing that variable in the body—happens so often that the language defines a second statement, the for statement, that abbreviates code that follows this pattern. We can rewrite this program using a for loop to sum the numbers from 1 through 10 as follows:
#include <iostream>int main(){ int sum = 0; // sum values from 1 through 10 inclusive for (int val = 1; val <= 10; ++val) sum += val; // equivalent to sum = sum + val std::cout << "Sum of 1 to 10 inclusive is " << ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access