Store a list of numbers whose length is only known at run time.
What to build
A program that allocates exactly as much memory as it needs.
Requirements
- Read
n, and allocate room fornints withmalloc. - Read the numbers into that memory.
- Print their average with two decimals, then free the memory.
Input
The first line has n. The second line has n whole numbers.
Output
One number with two decimals.
Constraints
n is from 1 to 100000. Each number is from -1000 to 1000.
Example
Input:
3
1 2 3
Output:
2.00
Why it works
The size comes from the input, so a fixed array would be either too small or wasteful. The heap gives exactly what was asked for.
Examples
Example 1 · Input
3 1 2 3
Expected output
2.00
Example 2 · Input
2 1 2
Expected output
1.50
Hints
Hint 1
malloc(n * sizeof(int)) makes room for n ints.
Hint 2
Use the pointer like an array.
Hint 3
free it before the program ends.
Solution
Show one correct solution (try it yourself first)
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n;
scanf("%d", &n);
int *a = malloc(n * sizeof(int));
if (a == NULL) {
return 1;
}
long long sum = 0;
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
sum += a[i];
}
printf("%.2f\n", (double)sum / n);
free(a);
return 0;
}