Arrays and Functions
Completed
Write int sum(int *a, int n) and double average(int *a, int n). Read an array and print both (average with 2 decimals).
Input
Line 1: n. Line 2: n integers.
Output
Two lines.
Example
Input
4 1 2 3 4
Output
10 2.50
Editor
C
Hints
Pass the array (it becomes a pointer) and its length.
Solution explanation
Functions can use pointer parameters with normal a[i] indexing.
Show solution
#include <stdio.h>
int sum(int *a, int n) {
int s = 0;
for (int i = 0; i < n; i++) s += a[i];
return s;
}
double average(int *a, int n) {
return (double) sum(a, n) / n;
}
int main() {
int n, a[100];
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%d", &a[i]);
printf("%d\n%.2f\n", sum(a, n), average(a, n));
return 0;
}