1: // Filename: MAXINTA3.CPP
2: // Purpose: Finds the maximum value in an array of integers.
3: // Uses an iterative function.
5: #include <iostream>
7: int MaxArrayValue(const int [], int, int);
9: int main()
10: {
11: int a1[10] = {5, -6, 12, 43, 17, -3, 29, 14, 35, 4};
12: int a2[10] = {-5, -6};
13: int a3[] = {1, 3, 5, 7, 9, 11};
14: int a4[] = {26, 24, 22, 20, 16, 12, 0};
16: cout << endl;
17: cout << "The maximum value in the first array is "
18: << MaxArrayValue(a1, 0, 9) << "." << endl;
19: cout << endl;
20: cout << "The maximum value in the second array is "
21: << MaxArrayValue(a2, 0, 9) << "." << endl;
22: cout << endl;
23: cout << "The maximum value in the third array is "
24: << MaxArrayValue(a3, 0, 5) << "." << endl;
25: cout << endl;
26: cout << "The maximum value in the fourth array is "
27: << MaxArrayValue(a4, 0, 6) << "." << endl;
28: cout << endl;
30: return 0;
31: }
34: int MaxArrayValue(/* in */ const int a[],
35: /* in */ int first,
36: /* in */ int last)
37: // Pre: The array "a" has been initialized, and
38: // 0 <= first <= last <= number of elements in "a" - 1.
39: // Post: Function value is the maximum value in the array "a"
40: // between the indices "first" and "last".
41: {
42: int i, maxVal;
44: maxVal = a[first];
45: for (i = first+1; i <= last; i++)
46: {
47: if (a[i] > maxVal)
48: maxVal = a[i];
49: }
50: return maxVal;
51: }