Returning Multiple Values: Use Call by Reference

//  this program reads in pairs of numbers and swaps them using a function
//  the pairs are printed both before and after swapping

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

//  prototype for swap function
void swap (int&, int&);

int main()
{
   int first;
   int second;
   ifstream numFile;

//  open the file and read the first pair of numbers

   numFile.open("nums.dat");
   numFile >> first >> second;
   while (numFile)
   {

//  for each pair of numbers, print them, swap them, and print them again
      cout << "Before Swapping ";
      cout << "First: " << first << " Second: " << second << endl;
      swap(first, second);
      cout << "After Swapping  ";
      cout << "First: " << first << " Second: " << second << endl << endl;
      numFile >> first >> second;
   }
   return 0;
}

//  this function exchanges the values of the parms
void swap(int& one, int& two)
{
   int temp;
   temp = one;
   one = two;
   two = temp;
}

File nums.dat:

10 20
50 25
39 41

Output:

Before Swapping First: 10 Second: 20
After Swapping  First: 20 Second: 10
Before Swapping First: 50 Second: 25
After Swapping  First: 25 Second: 50
Before Swapping First: 39 Second: 41
After Swapping  First: 41 Second: 39


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

© Copyright Emmi Schatz 2002