Advertisement
reellearning

Passing Arrays to Functions in C++

Jun 27th, 2012
4,271
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.03 KB | None | 0 0
  1. /*
  2.  * passingarrays.cpp
  3.  *
  4.  *  Created on: Jun 25, 2012
  5.  *      Author: Derek
  6.  *
  7.  *  Example of passing arrays to functions
  8.  */
  9.  
  10.  
  11. #include <iostream>
  12. using namespace std;
  13.  
  14. void printArray(double[], int);
  15. void userInputArray(double array[], int size);
  16.  
  17.  
  18. int main()
  19. {
  20.  
  21.     double rainfall[5];
  22.  
  23.     rainfall[0] = 2.3;
  24.     rainfall[1] = 0.3;
  25.     rainfall[2] = 0.0;
  26.     rainfall[3] = 4.1;
  27.     rainfall[4] = 0.5;
  28.  
  29.     printArray(rainfall, 5);
  30.  
  31.     userInputArray(rainfall, 5);
  32.  
  33.     printArray(rainfall, 5);
  34.  
  35. }
  36. // The first formal parameter could also be
  37. // written as double* array since a pointer
  38. // to the first element is what is really
  39. // passed to the array. (Ditto for function
  40. // below)
  41. void printArray(double array[], int size)
  42. {
  43.     for(int i = 0; i < size; i++)
  44.     {
  45.         cout << array[i] << endl;
  46.     }
  47. }
  48.  
  49. void userInputArray(double array[], int size)
  50. {
  51.     for(int i = 0; i < size; i++)
  52.     {
  53.         cout << "Enter a rainfall amount: " << endl;
  54.         cin >> array[i];
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement