Sample Program: Nested Loops

//  This program prints lines of stars. It reads numbers from a file; each
//  number tells how many stars to print on the next line.

#include <iostream.h>
#include <iomanip.h>
#include <fstream.h>

int main()
{
   int starCount;
   int counter;
   ifstream starFile;

//  open the file with the star count for each line
   starFile.open("starcnt.dat");

//  each iteration of the outer loop prints a line of stars
   starFile >> starCount;
   while (starFile)
   {

//  each iteration of the inner loop prints one star
      counter = 1;
      while (counter <= starCount)
      {
         cout << '*';
         counter++;
      }

//  end the line of stars and get the count for the next line
      cout << endl;
      starFile >> starCount;
   }

   return 0;
}

File starcnt.dat

5
10
15
10
5

Output

*****
**********
***************
**********
*****


Email Me | Office Hours | My Home Page | Department Home | MCC Home Page

© Copyright Emmi Schatz 2002