sum_arr2.c 598 B

12345678910111213141516171819202122232425262728
  1. /* sum_arr2.c -- sums the elements of an array */
  2. #include <stdio.h>
  3. #define SIZE 10
  4. int sump(int * start, int * end);
  5. int main(void)
  6. {
  7. int marbles[SIZE] = {20,10,5,39,4,16,19,26,31,20};
  8. long answer;
  9. answer = sump(marbles, marbles + SIZE);
  10. printf("The total number of marbles is %ld.\n", answer);
  11. return 0;
  12. }
  13. /* use pointer arithmetic */
  14. int sump(int * start, int * end)
  15. {
  16. int total = 0;
  17. while (start < end)
  18. {
  19. total += *start; // add value to total
  20. start++; // advance pointer to next element
  21. }
  22. return total;
  23. }