C++ Notes: Loop Example - Line of stars - count down

This program reads an integer and prints a line with that number of stars (asterisks). It counts down from the number it reads in. The outer loop reads these integers until an EOF or bad input.

Implemented with a while loop

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
// loops/line-of-stars-down.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 n down to 0.
        while (n > 0) {
            cout << "*";
            n--;
        }
        cout << endl;
    }
    return 0;
}
The text from the above example can be selected, copied, and pasted into an editor.

Implemented as a for loop

Because the variable n already has a value when we start the inner loop, there is no need for an initialization clause. The for statement requires three clauses separated by semicolons; just leave any unneeded clause blank.
  1 
  2 
  3 
  4 
  5 
  6 
    while (cin >> n) {
        for ( ; n > 0; n--) {
            cout << "*";
        }
        cout << endl;
    }
The text from the above example can be selected, copied, and pasted into an editor.