C: Sum of an array

Write a function that adds up an array it is given.

What to build

A function with an array parameter and a length.

Requirements

  • Write int sum(const int *a, int n).
  • Read the numbers and print their sum.

Input

The first line has n. The second line has n whole numbers.

Output

One number.

Constraints

n is from 1 to 100. Each number is from -1000 to 1000.

Example

Input:

3
1 2 3

Output:

6

Why it works

The function only needs the address of the first element and the length. const promises that it will not change the array.

Examples

Example 1 · Input
3
1 2 3
Expected output
6
Example 2 · Input
1
-5
Expected output
-5

Hints

Hint 1

The function receives a pointer and a length.

Hint 2

Use a loop, and a[i] works on a pointer too.

Solution

Show one correct solution (try it yourself first)
#include <stdio.h>

int sum(const int *a, int n) {
    int total = 0;
    for (int i = 0; i < n; i++) {
        total += a[i];
    }
    return total;
}

int main(void) {
    int n, a[100];
    scanf("%d", &n);
    for (int i = 0; i < n; i++) scanf("%d", &a[i]);
    printf("%d\n", sum(a, n));
    return 0;
}

Lesson: Pointers and arrays →