EXAMPLE PROGRAM • ARRAYS AS PARAMETERS

 

 

#include <iostream.h>

#include <iomanip.h>

#include <apvector.h>

 

void printList (const apvector<int> &);

void squareList (apvector<int> &);

void rotateList (apvector<int>);

 

const int MAX=6;

 

main ()

{

      apvector<int>  data(MAX);

      int loop;

 

      for (loop=0; loop < MAX; loop++)

            data[loop] = loop;   // initialize array

      cout << "Array initialized:  ";

      printList (data);   // print array in ascending order

      squareList (data);

      cout << "Array after call of squareList:  ";

      printList (data);

      rotateList (data);

      cout << "Array after call of rotateList:  ";

      printList (data);  // print list again

      return 0;

}

 

void printList (const apvector<int> &list)

/*  list is a const reference parameter.  list is the same array as

      array data in function main, except no changes can be made

      to the array because of the const qualifier.  This gives us the

      efficiency of reference parameters with const protection*/

{

      int index;

 

      for (index = 0; index < MAX; index++)

            cout << list[index] << "   ";

      cout << endl << endl;

}

 

void squareList (apvector<int> &list)

/*  Array list is a local alias for array data in function main.  Any

      reference to local list is a reference to array data in function main.  */

{

      int index;

 

      for (index=0; index < MAX; index++)

            list[index] = list[index] * list[index];

}

 


void rotateList (apvector<int> list)

/*  This function is working with a local copy of the array passed

      as an argument.  Changes to local array list will have no effect

      on the array data in function main.  This function will shift each

      value one cell to the right.  The value in list[MAX-1] will be

      moved to list[0].  Before the function is completed, printList will

      be called.  The point of this function is to illustrate an array as

      a value parameter.  */

{

      int temp = list[MAX-1], loop;

 

      for (loop=MAX-1; loop>0; loop--)

            list[loop] = list[loop-1];

      list[0] = temp;

      cout << "Inside of rotateList:  ";

      printList (list);

}

 

 

 

Run output:

 

Array initialized:   0   1   2   3   4   5

 

Array after call of squareList:   0   1   4   9  16  25

 

Inside of rotateList:  25   0   1   4   9  16

 

Array after call of rotateList:   0   1   4   9  16  25