Sunteți pe pagina 1din 10

Passing an Array to a

Function

Arrays Using for loops


For loops are a more compact way of
processing loops
Instead of this:
You can do this:
cin>>a[0];
for (k=0; k<6; k++)
cin>>a[1];
cin>>a[k];
cin>>a[2];
cin>>a[3];
cin>>a[4];
cin>>a[5];
2

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:
You can do this:
a[0]=a[9];
for (k=0; k<5; k++)
a[1]=a[8];
a[k] = a[9-k];
a[2]=a[7];
a[3]=a[6];
a[4]=a[5];
3

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];
4

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[]
This would be a parameter

We dont want to specify the size so


function can work with different sized
arrays. Size comes in as a second
parameter
6

Passing an Array to a Function


#include <iostream.h>

An int array parameter


of unknown size

int Display(int data[], int N)


{ int k;
cout<<Array contains<<endl;
for (k=0; k<N; k++)
cout<<data[k]<< ;
cout<<endl;
The size of the array
}
int main()
{
int a[4] = { 11, 33, 55, 77 };
Display(a, 4);
}
The array argument,
7 no []

Passing an Array to a Function

#include <iostream.h>
int sum(int data[], int n);

//PROTOTYPE

The array argument, no


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


8

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;
}
9

Thats a wrap !
What we learned today:
What are arrays
Array indexing
Array initialization
Array index out of bound error
Passing arrays to functions

10

S-ar putea să vă placă și