Sample Program: Nested Loops

//  This program prints lines of stars. For each line of stars it reads two
//  numbers from a file. The first number tells how many stars to print on
//  the next line. The second number tells how many blanks to print before
//  printing the stars.

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

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

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

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

//  each iteration of this loop prints one blank
      counter = 1;
      while (counter <= spaceCount)
      {
         cout << ' ';
         counter++;
      }

//  each iteration of this 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 >> spaceCount;
   }

   return 0;
}

File starspc.dat

5 5
11 2
15 0
11 2
5 5

Output

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


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

© Copyright Emmi Schatz 2002