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

This program reads an integer and prints a line with that number of stars (asterisks). A new variable, i, is used to count from 1 up to n. The outer loop reads these integers until an EOF or bad input.

Implemented as a while loop

  1 
  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;
}
The text from the above example can be selected, copied, and pasted into an editor.

Implemented as a for loop

The most common way to write a loop that counts is the for 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 << "*";
}