Sample Program: Void Functions

//  This program calculates the total cost when three items are
//  purchased. The program uses functions to fancy up the output.
//  Notice that function calls are separate statements

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

//  prototypes for our printing functions
void printHeading();
void printStars();

int main()
{
   int price1, int price2, int price3;
   int total;

//  read in the cost of the three items and calculate the total cost
   printStars();     // function call
   cout << "Enter the cost of the items:" << endl;
   cout << "   Item 1: ";
   cin >> price1;
   cout << "   Item 2: ";
   cin >> price2;
   cout << "   Item 3: ";
   cin >> price3;
   total = price1 + price2 + price3;

//  print out the costs and the total
   printHeading();     // function call
   cout << "     Item 1:" << setw(6) << price1 << endl;
   cout << "     Item 2:" << setw(6) << price2 << endl;
   cout << "     Item 3:" << setw(6) << price3 << endl;
   cout << endl << "     Total: " << setw(6) << total << endl;
   printStars();      // function call
   return 0;
}

//  function definition for printHeading
//  this function prints a nicely formatted heading for the output
void printHeading()       // function header
{
   cout << endl << endl;
   cout << "*****************************" << endl;
   cout << "        Cost of Items" << endl;
   cout << "*****************************" << endl << endl;
}

//  function definition for printStars
//  this function prints a line of stars
void printStars()        // function header
{
   cout << "*****************************" << endl;
}

Sample Execution

*****************************
Enter the cost of the items:
   Item 1: 45
   Item 2: 60
   Item 3: 15


*****************************
        Cost of Items
*****************************

     Item 1:    45
     Item 2:    60
     Item 3:    15

     Total:    120
*****************************


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

© Copyright Emmi Schatz 2002