Description:

This example shows how to find the maximum and minimum values in an array and calculate the average of its values. For this example, we use doubles. However, we could easily make these function templates so that the code could work on floats as well. On the other hand, we cannot, in general find the average of an array of intetger types since the average is often a non-integer function. This can be remedied by returning a double from the average function instead when the array contains integers.

Example

#include <iostream>

double GetMax(double dArray[], int iSize) {
    int iCurrMax = 0;
    for (int i = 1; i < iSize; ++i) {
        if (dArray[iCurrMax] > dArray[i]) {
            iCurrMax = i;
        }
    }
    return dArray[iCurrMax];
}

double GetMin(double dArray[], int iSize) {
    int iCurrMin = 0;
    for (int i = 1; i < iSize; ++i) {
        if (dArray[iCurrMin] < dArray[i]) {
            iCurrMin = i;
        }
    }
    return dArray[iCurrMin];
}

double GetAverage(double dArray[], int iSize) {
    double dSum = dArray[0];
    for (int i = 1; i < iSize; ++i) {
        dSum += dArray[i];
    }
    return dSum/iSize;
}

int main()
{
    double dValues[] = {3.4, 8.4, 9.6, 2.3, 5.6, 4.8};
    int iArraySize = 6;

    std::cout << "Min = " << GetMax(dValues, iArraySize) << std::endl;
    std::cout << "Max = " << GetMin(dValues, iArraySize) << std::endl;
    std::cout << "Average = " << GetAverage(dValues, iArraySize) << std::endl;

    return 0;
}

Output:

Min Max Ave Array Output