Source of max_of_integer_array.cpp


  1: /** @file max_of_integer_array.cpp
  2: Finds the maximum value in an array of integers.
  3: Uses a recursive function which applies one recursive call
  4: to a portion of the array that becomes smaller and smaller.
  5: */

  7: #include <iostream>
  8: using namespace std;

 10: #include "utilities.h"
 11: using Scobey::Pause;

 13: int maxArrayValue
 14: (
 15:     const int a[], //in
 16:     int first,     //in
 17:     int last       //in
 18: )
 19: /**<
 20: Compute the maximum value from the index interval
 21: [first, last] in the array.
 22: @return The maximum value from the interval [first, last].
 23: @param a An array of integers.
 24: @param first The lower index of the interval to be examined.
 25: @param last The upper limit of the interval to be examined.
 26: @pre The array a has been initialized, and
 27: 0 <= first <= last <= (number of elements in a) - 1.
 28: @post No side effects.
 29: */
 30: {
 31:     if (first == last)
 32:         return a[first];
 33:     else
 34:     {
 35:         int maxOfRest = maxArrayValue(a, first+1, last);
 36:         return (a[first] > maxOfRest) ? a[first] : maxOfRest;
 37:     }
 38: }

 40: int main()
 41: {
 42:     cout << "\nThis program illustrates the application "
 43:         "of recursion to an array.\n";
 44:     Pause();

 46:     int a1[10] = {5, -6, 12, 43, 17, -3, 29, 14, 35, 4};
 47:     cout << "The maximum value in the first array is "
 48:         << maxArrayValue(a1, 0, 9) << ".\n";
 49:     Pause();

 51:     int a2[10] = {-5, -6};
 52:     cout << "The maximum value in the second array is "
 53:         << maxArrayValue(a2, 0, 9) << ".\n";
 54:     Pause();

 56:     int a3[]   = {1, 3, 5, 7, 9, 11};
 57:     cout << "The maximum value in the third array is "
 58:         << maxArrayValue(a3, 0, 5) << ".\n";
 59:     Pause();

 61:     int a4[]   = {26, 24, 22, 20, 16, 12, 0};
 62:     cout << "The maximum value in the fourth array is "
 63:         << maxArrayValue(a4, 0, 6) << ".\n";
 64:     Pause();
 65: }