Sample Program: Function with Local Variable

//  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 <fstream.h>

void starprint(int);

int main()
{
   int starCount;
   ifstream starFile;

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

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

//  call starprint function to print one line of stars
      starprint(starCount);
      starFile >> starCount;
   }

   return 0;
}

//  print a line of stars; parm gives the number of stars to print
void starprint(int starCount)
{
   int counter = 1;
   while (counter <= starCount)
   {
      cout << '*';
      counter++;
   }

//  end the line of stars
   cout << endl;
}

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