Challenge: Dynamic Average
Completed
Read n, then use malloc to make room for exactly n ints. Read the numbers, print how many are bigger than the average, then free the memory.
Input
n (1 ≤ n ≤ 1000), then n integers.
Output
One number: how many are above the average.
Example
Input
5 1 2 3 4 5
Output
2
Editor
C
Hints
int *nums = malloc(n * sizeof(int));
Two loops: one to read and add, one to count.
Solution explanation
The array is exactly as big as the input needs, and it is freed at the end.
Show solution
#include <stdio.h>
#include <stdlib.h>
int main() {
int n;
scanf("%d", &n);
int *nums = malloc(n * sizeof(int));
int total = 0;
for (int i = 0; i < n; i++) {
scanf("%d", &nums[i]);
total += nums[i];
}
double avg = (double) total / n;
int above = 0;
for (int i = 0; i < n; i++) {
if (nums[i] > avg) {
above++;
}
}
printf("%d\n", above);
free(nums);
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module