C bootcamp · Lab 50

Sum an array

easyArrays10 minLesson: Arrays

Read the question, write C on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Read n then n integers. Print their sum.

Input. n, then n ints.

Output. One integer sum.

Examples

Example 1
Input
3
1 2 3
Output
6
Example 2
Input
1
42
Output
42
Hint
  1. Accumulate while reading.
Show correct code

Peek only after you have tried. You can still Check your own version.

#include <stdio.h>

int main(void) {
  int n;
  if (scanf("%d", &n) != 1) return 1;
  long sum = 0;
  for (int i = 0; i < n; i++) {
    int x;
    if (scanf("%d", &x) != 1) return 1;
    sum += x;
  }
  printf("%ld\n", sum);
  return 0;
}
main.cC17 · gcc · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.