310 likes | 1.1k Views
Passing an Array to a Function. Arrays – Using for loops. For loops are a more compact way of processing loops Instead of this: cin>>a[0]; cin>>a[1]; cin>>a[2]; cin>>a[3]; cin>>a[4]; cin>>a[5];. You can do this: for (k=0; k<6; k++) cin>>a[k];. Arrays – Using for loops.
E N D
Arrays – Using for loops • For loops are a more compact way of processing loops • Instead of this: cin>>a[0]; cin>>a[1]; cin>>a[2]; cin>>a[3]; cin>>a[4]; cin>>a[5]; You can do this: for (k=0; k<6; k++) cin>>a[k];
Arrays – Using for loops • Anytime you see a pattern in what you are doing, you can replace it with a for-loop: • Instead of this: a[0]=a[9]; a[1]=a[8]; a[2]=a[7]; a[3]=a[6]; a[4]=a[5]; You can do this: for (k=0; k<5; k++) a[k] = a[9-k];
Advantage of for loops • More compact, Saves typing • Easier to modify if size of array changes • Since for loops are so common, a technique of using a const int for size of the array: const int SIZE=10; int k, data[SIZE]; for (k=0; k<SIZE; k++) cin>>data[k];
Arrays – NOTE • Initializing an array with more values than the size of the array would lead to a run-time (not compiler!) error • Referring to an array index larger than the size of the array would lead to a run-time (not compiler!) error
Passing an Array to a Function • When passing an array to a function, we need to tell the compiler what the type of the array is and give it a variable name, similar to an array declaration float a[] • We don’t want to specify the size so function can work with different sized arrays. Size comes in as a second parameter This would be a parameter
Passing an Array to a Function An int array parameter of unknown size #include <iostream.h> int Display(int data[], int N) { int k; cout<<“Array contains”<<endl; for (k=0; k<N; k++) cout<<data[k]<<“ “; cout<<endl; } int main() { int a[4] = { 11, 33, 55, 77 }; Display(a, 4); } The size of the array The array argument, no []
Passing an Array to a Function The array argument, no [] #include <iostream.h> int sum(int data[], int n); //PROTOTYPE void main() { int a[] = { 11, 33, 55, 77 }; int size = sizeof(a)/sizeof(int); cout << "sum(a,size) = " << sum(a,size) << endl; } int sum(int data[], int n) { int sum=0; for (int i=0; i<n;i++) sum += data[i]; return sum; } An int array parameter of unknown size The size of the array
Arrays are always Pass By Reference • Arrays are automatically passed by reference. Do not use &. • If the function modifies the array, it is also modified in the calling environment void Zero(int arr[], int N) { for (int k=0; k<N; k++) arr[k]=0; }
That’s a wrap ! • What we learned today: • What are arrays • Array indexing • Array initialization • Array index out of bound error • Passing arrays to functions