// Mr. Minich
// CMPSC 201
// Ch. 5 Demo Program #1
// January 30, 2000 // Purpose - to illustrate the use of the for loop
#include <iostream> using namespace std; int main() { int loopCounter = 0; // loop variable for (loopCounter = 1; loopCounter <= 10; loopCounter++) { cout << loopCounter << endl; }
// The values 1 through and including 10 are displayed. // Notice the use of blank lines above and below the for loop for readability.
for (loopCounter = 1; loopCounter < 10; loopCounter++) { cout << loopCounter << endl; }
// The values 1 through and including 9 are displayed BUT // loopCounter's final value is 10. Can you explain why? for (int loop = 0; loop != 10; loop++) { cout << loop << endl; } // The loop variable loop is declared and initialized to the // starting value of 0 within the initializing expression // of the for loop. The control expression loop != 10 is very // dangerous here. The loop does stop iterating when loop // increments to the value of 10 but if, for whatever reason, // loop "skipped over" the value of 10, the loop would iterate // forever. In that case, the for loop would be an infinite // loop and the C++ program would never stop executing!
// Does the value of 10 print in this loop?
return 0;
}// end of main