Complementary task for topic: 3

M Nemeth · 2023-08-29 15:21:04.616219'

Arrays: max, min, avg

Arrays: max, min, avg

Write a C program that prompts the user to enter an integer array of size 5 and calculates the maximum, minimum, and average of the array elements.

Hint: Watch out for the initials for min and max!

Solution
#include 

#define SIZE 5

int main() {
    int numbers[SIZE];
    int max, min, sum = 0;
    double average;
    
    printf("Enter %d integers:\n", SIZE);
    
    for (int i = 0; i < SIZE; i++) {
        scanf("%d", &numbers[i]);
        
        if (i == 0) {
            max = min = numbers[i];
        } else {
            if (numbers[i] > max) {
                max = numbers[i];
            }
            if (numbers[i] < min) {
                min = numbers[i];
            }
        }
        
        sum += numbers[i];
    }
    
    average = (double)sum / SIZE;
    
    printf("Maximum element: %d\n", max);
    printf("Minimum element: %d\n", min);
    printf("Sum of the array elements: %d\n", sum);
    printf("Average of the array elements: %.2f\n", average);
    
    return 0;
}



Explanation
In this example, the program declares an integer array numbers of size SIZE, which is set to 5 using the #define directive. It also declares variables max, min, sum, and average to store the maximum, minimum, sum, and average of the array elements, respectively.

The program prompts the user to enter SIZE number of integers using scanf() within a for loop. Each input is stored in the corresponding index of the numbers array.

While reading the inputs, the program simultaneously finds the maximum and minimum elements of the array using an if-else construct.

The sum of all the entered numbers is calculated using the sum variable, and the average is calculated by dividing the sum by the size of the array.
< < previous    next > >