Advertisement
Guest User

Untitled

a guest
Apr 18th, 2014
33
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.89 KB | None | 0 0
  1. //Write a function that computes the average value of an array of floating-point data:
  2. //double average(double* a, int size)
  3. //In the function, use a pointer variable, not an integer index, to traverse the array
  4. //elements.
  5.  
  6.  
  7.  
  8. #include <iostream>
  9.  
  10. using namespace std;
  11.  
  12.  
  13. double average(double* a, int size)
  14.  
  15. {
  16. double total = 0;
  17. double* p = a;
  18. // p starts at the beginning of the array
  19. for (int i = 0; i < size; i++)
  20. {
  21. total = total + *p;
  22. // Add the value to which p points
  23. p++;
  24. // Advance p to the next array element
  25. }
  26. return total / size;
  27. }
  28.  
  29. int main()
  30. {
  31. double array[5] = {1,2,3,4,5};
  32. std::cout << average(array, 5);
  33. }
  34.  
  35. double average(double* a, int size) {
  36.  
  37. double total = 0;
  38.  
  39. // *(a + i) starts at the beginning of the array
  40. for (int i = 0; i < size; i++)
  41. {
  42. total = total + *(a + i);
  43. }
  44. return total / size;
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement