/* * Program to print numbers from input in reverse order and compute * their sum. (Not a very sensible program, but an example of using * an array.) * * Input: Zero or more integers, read from standard input, terminated * by anything other than a number. * * Output: Input numbers in reverse order, then sum of input numbers * (zero if none). */ #include #define ARRAY_SIZE 100 /* * Compute sum of array elements: * returns sum of nums[0] through nums[count-1]. */ int sum_of_elements(int count, int nums[]) { int i; int running_total = 0; for (i = 0; i < count; ++i) { running_total += nums[i]; } return running_total; } /* * Main program */ int main(void) { int input; int sum; int index = 0; int nums[ARRAY_SIZE]; printf("enter numbers to add (no more than %d), non-number to end:\n", ARRAY_SIZE); while ((index < ARRAY_SIZE) && (scanf("%d", &input) == 1)) { nums[index] = input; index += 1; } sum = sum_of_elements(index, nums); printf("sum of elements = %d\n", sum); return 0; }