Read n and then n numbers. Store them in memory from malloc, print their sum, then print them in reverse order. Free the memory before the program ends.
What to build
A program that stores numbers on the heap.
Requirements
- Allocate the array with
malloc. - Print the sum, then the numbers in reverse.
- Free the memory.
Input
The first line has n (1 ≤ n ≤ 100000). The second line has n whole numbers between -1000 and 1000.
Output
Two lines: the sum, then the numbers in reverse order separated by spaces.
Constraints
n is from 1 to 100000.
Example
Input:
3
1 2 3
Output:
6
3 2 1
Why it works
The memory is requested only once n is known, and freeing it returns it to the system when it is no longer needed.
Examples
Example 1 · Input
3 1 2 3
Expected output
6 3 2 1
Example 2 · Input
1 -5
Expected output
-5 -5
Hints
Hint 1
After reading n, allocate with int *a = malloc(n * sizeof(int));
Hint 2
Print in reverse, then free(a) before main returns.
Hint 3
n can be up to 100000, too many for a fixed small array.
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("%lld\n", sum);
for (int i = n - 1; i >= 0; i--) printf("%d%s", a[i], i > 0 ? " " : "\n");
free(a);
return 0;
}