Introducing the for Loop
Circumstances often call upon a program to perform repetitive tasks, such as adding together the elements of an array one by one or printing some paean to productivity twenty times. The C++ for loop makes such tasks easy to do. Let's look at a loop in Listing 5.1, see what it does, and then discuss how it works.
Listing 5.1. forloop.cpp
// forloop.cpp -- introducing the for loop #include <iostream> using namespace std; int main() { int i; // create a counter // initialize; test ; update for (i = 0; i < 5; i++) cout << "C++ knows loops.\n"; cout << "C++ knows when to stop.\n"; return 0; } |
Here is the output:
C++ knows loops. C++ knows loops. C++ knows loops. C++ knows loops. C++ knows loops. C++ knows when to stop. ...
Get C++ Primer Plus, Fourth 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.