#include "assert.h" #include "stdio.h" #include /* Writes the sum of the array a of length n of integers * into sum. Return 0 if successful and -1 if either of a * or sum is NULL or n < 0. */ int sum(int * a, int n, int * sum) { if (!a || n < 0 || !sum) return -1; *sum = 0; while (n > 0) { *sum += *a; a++; n--; } return 0; } #define MAX_N 100 int main() { int numbers[MAX_N]; int num, s, err, ret; int i = 0; while (1) { // check if out of space if (i == MAX_N) { printf("Too many numbers.\n"); return -1; } // read an integer ret = scanf("%d", &num); // check if stdin has closed if (ret == EOF) // stdin has closed, so exit the loop break; // check if scanf returned 0, indicating bad input if (ret == 0) { printf("Expected an integer.\n"); return -1; } // add the input to the array numbers[i] = num; i++; } // compute the sum err = sum(numbers, i, &s); assert (!err); printf("Sum: %d\n", s); return 0; }