Array Functions

Array Functions

Make a program that lets the user input numbers into an array and present the average, max, min, median and sum of the array; using these functions.

float get_average(float arr[], int size);
float get_max(float arr[], int size);
float get_min(float arr[], int size);
float get_sum(float arr[], int size);

Hint

float get_average(float arr, int size);

Sum all elements of the array and divide by the

float get_max(float arr, int size); float get_min(float arr , int size);

Store the max/min number as the first element of the array. Loop through the array and assign the max/min value with the current element if it is larger/smaller.

Answer

#include <iostream>
#include <algorithm>

float get_sum(float arr[], int size) {
    float sum = 0;
    for (int i = 0; i < size; i++) {
        sum += arr[i];
    }
    return sum;
}

float get_average(float arr[], int size) {
    float sum = 0;
    for (int i = 0; i < size; i++) {
        sum += arr[i];
    }
    return sum / size;
}

float get_max(float arr[], int size) {
    float max = arr[0];
    for (int i = 1; i < size; i++) {
        if (arr[i] > max) {
            max = arr[i];
        }
    }
    return max;
}

float get_min(float arr[], int size) {
    float min = arr[0];
    for (int i = 1; i < size; i++) {
        if (arr[i] < min) {
            min = arr[i];
        }
    }
    return min;
}

int main() {
    int n;
    std::cout << "Enter number of elements: ";
    std::cin >> n;

    float arr[n];
    for (int i = 0; i < n; i++) {
        std::cout << "Enter element " << i + 1 << ": ";
        std::cin >> arr[i];
    }

    std::cout << "Average: " << get_average(arr, n) << std::endl;
    std::cout << "Maximum: " << get_max(arr, n) << std::endl;
    std::cout << "Minimum: " << get_min(arr, n) << std::endl;
    std::cout << "Sum: " << get_sum(arr, n) << std::endl;
}

Reusing get_sum in the get_average function is perfectly fine.



float get_average(float arr[], int size) {
    return get_sum(arr, size) / size;
}
Questions