Programming Language I (Spring 2016)

Lecture Notes : Arrays Arrays 1. Array is a block of consecutively reserved locations and can be accessed with the same variable name.

Figure 1: Example of Arrays in memory (int x[5])

2. It can be thought of as a collection of variables but can be accessed via the same name and index. 3. When declaring arrays, specify • Name • Datatype of the array • Number of elements Datatype ype arrayName[ arraySize ]; Ex. int c[ 10 ]; // array of 10 integers at locations indexed from 0 to 9 float d[ 3284 ]; // array of 3284 floats at locations indexed from 0 to 3283 4. As any variable we can declare it, read value from it, write value in it Statement Declaration Reading

Single-location Variable int x; cin>>x;

Writing

coutx[0]; //will read the value of a single location at index 0 coutx[0] , cin>>x[1] , cin>>x[2],…….and cin>>x[24]. 2. It means we need cin>>x[i] where i is incrementing its value each time starting from 0 to 24. Which statement can perform this???? It is the repetition statement like “for statement” so the code could be written as follows: Code int main() { int i,x[25]; for(i=0;i>x[i]; } return 0; } Hint: The arrow in figure 1 is actually expressed in memory as the address of the first location of the array (address of x[0]) and the array variable is called a pointer and points to the first location of the array as shown in figure 2. Pointers will be extensively studied in the next lecture.

Programming Language I (Spring 2016)

Lecture Notes : Arrays

Figure 2

Passing arrays to functions 1. Array can be passed to a function with empty square brackets like in the following function header as the size of the array is not required between the array brackets. If it is included, the he compiler ignores it. void oid read_array (int x[]) 2. Any modification to the array contents inside the function is known to the caller function. How?? Because it uses call by reference. 3. The caller function as ((main function) should call the read_array function as follows int main() { int y[24]; read_array(y); } Hint: it is recommended to include a second parameter contains the array size in the function header like void oid read_array (int x[],int size); int main() { int y[24]; read_array(y,24 ,24); }

Programming Language I (Spring 2016)

Lecture Notes : Arrays Example void modifyArray( int [], int ); void modifyElement( int ); int main() { int arraySize = 5; // size of array a int a[ 5 ] = { 0, 1, 2, 3, 4 }; // initialize array a cout