/* * 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 #include #define MAXNUMS 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 sum = 0; for (i = 0; i < count ; ++i) { sum += nums[i]; } return sum; } /* * Main program */ int main(void) { int nums[MAXNUMS]; int input; int count = 0; int i; printf("enter numbers to add (no more than %d), non-number to end:\n", MAXNUMS); while ((scanf("%d", &input) == 1) && (count < MAXNUMS)) { nums[count] = input; count += 1; } printf("in reverse order, you entered:\n"); for (i = count-1 ; i >= 0 ; --i) { printf("%d\n", nums[i]); } printf("sum of elements = %d\n", sum_of_elements(count, nums)); return EXIT_SUCCESS; }