Please send questions to
st10@humboldt.edu .
//----------------------------------------------------------------------
// File: recMax.cpp
// Name: Sharon M. Tuttle
// last modified: 1-29-05
//
// Contract: recMax -> int[] int -> int
//
// Purpose: find the largest element in the first <size> elements
// of non-empty integer array <arr>.
//
// preconditions:
// * size > 0
// * size <= number of elements in arr
//
// postconditions:
// * will return the largest element amongst those in the
// range [arr[0], arr[size-1]] (inclusive)
//
// Examples: for int exArr[] = {50, 13, 130, 2, 27, 169, -5, 16, 22},
// recMax(exArr, 9) == 169
// recMax(exArr, 1) == 50
// recMax(exArr, 3) == 130
//-------------------------------------------------------------------
#include <cassert>
#include <cmath>
using namespace std;
int recMax(int arr[], int size)
{
int restMax;
// check preconditions that you are able to
assert(size > 0);
// base case: if only 1 element, max IS that element;
if (size == 1)
{
return arr[0];
}
// recursive case: otherwise, maximum is whatever is larger:
// the last element, or the maximum of all of the rest of
// the elements;
else
{
restMax = recMax(arr, (size-1));
if (arr[size-1] > restMax)
{
return arr[size-1];
}
else
{
return restMax;
}
//return max(arr[size-1], recMax(arr, (size-1));
}
}