i
, is used to count from 1 up to n
.
The outer loop reads these integers until
an EOF or bad input.
while
loop1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// loops/line-of-stars-up.cpp - Read int and print that many stars on a line. // Fred Swartz = 1003-08-23 #include <iostream> using namespace std; int main() { int n; while (cin >> n) { //--- Loop counting i up from 1 to n. int i = 1; // Initialize counter. while (i <= n) { // Test counter. cout << "*"; i++; // Increment counter. } cout << endl; } return 0; } |
for
loopfor
loop
because it combines the intitialization, testing, and increment
in one statement. This makes the program easier to read and maintain.
Here is the inner while
loop rewritten as a for
loop.
1 2 3 |
for (int i=1; i<=n; i++) { cout << "*"; } |