QUESTION 12 · Array Basics
Write a C program to find minimum, maximum and average in an integer array.
5 marksAnswer in brief
The minimum and maximum can be updated while traversing an array. The average is the total divided by the number of elements.
Algorithm
- Read a non-empty array.
- Set minimum and maximum to a[0] and sum to a[0].
- Scan indices 1 through n - 1. Update each extreme when needed and add the current value to sum.
- Calculate average as (double)sum / n and display the results.
Worked trace
For 4, -2 and 7, both extremes start at 4 and sum starts at 4. Reading -2 changes minimum to -2 and sum to 2. Reading 7 changes maximum to 7 and sum to 9. Average is 9.0 / 3 = 3.0.
Important cases
A single-element list has the same minimum, maximum and average value. Repeated equal values need no special replacement. The list can contain negative values and need not be sorted. An empty list is rejected because this method needs a first element and the average must not divide by zero.
Preserving fractions
Casting sum to double before division allows a fractional average. Casting after integer division would not restore a discarded fraction. long long stores the bounded sample’s total safely, and the result is displayed with two decimal places.
Complexity
One scan examines each value once. A fixed number of comparisons and an addition are performed per element, giving O(n) time. minimum, maximum, sum and average occupy fixed extra storage, so auxiliary space is O(1), excluding the input array.
C program and output
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int main(void)
{
int n, a[20];
if (scanf("%d", &n) != 1 || n < 1 || n > 20) {
puts("Unsupported input"); return 1;
}
for (int i = 0; i < n; ++i) {
if (scanf("%d", &a[i]) != 1 || a[i] < -10000 || a[i] > 10000) {
puts("Unsupported input"); return 1;
}
}
int minimum = a[0], maximum = a[0];
long long sum = a[0];
for (int i = 1; i < n; ++i) {
if (a[i] < minimum) { minimum = a[i]; }
if (a[i] > maximum) { maximum = a[i]; }
sum += a[i];
}
printf("Minimum = %d, maximum = %d, average = %.2f\n",
minimum, maximum, (double)sum / n);
return 0;
}
Sample input and output
Input
3
4 -2 7
Output
Minimum = -2, maximum = 7, average = 3.00