arrfun4.cpp 927 B

12345678910111213141516171819202122232425262728293031
  1. // arrfun4.cpp -- functions with an array range
  2. #include <iostream>
  3. const int ArSize = 8;
  4. int sum_arr(const int * begin, const int * end);
  5. int main()
  6. {
  7. using namespace std;
  8. int cookies[ArSize] = {1,2,4,8,16,32,64,128};
  9. // some systems require preceding int with static to
  10. // enable array initialization
  11. int sum = sum_arr(cookies, cookies + ArSize);
  12. cout << "Total cookies eaten: " << sum << endl;
  13. sum = sum_arr(cookies, cookies + 3); // first 3 elements
  14. cout << "First three eaters ate " << sum << " cookies.\n";
  15. sum = sum_arr(cookies + 4, cookies + 8); // last 4 elements
  16. cout << "Last four eaters ate " << sum << " cookies.\n";
  17. // cin.get();
  18. return 0;
  19. }
  20. // return the sum of an integer array
  21. int sum_arr(const int * begin, const int * end)
  22. {
  23. const int * pt;
  24. int total = 0;
  25. for (pt = begin; pt != end; pt++)
  26. total = total + *pt;
  27. return total;
  28. }