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 " << ...
Get C++ Primer, Fifth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.