Lecture 15: Projects Using Similar Data. What is an Array? An array is a data structure consisting...
-
Upload
julius-bradley -
Category
Documents
-
view
214 -
download
0
Transcript of Lecture 15: Projects Using Similar Data. What is an Array? An array is a data structure consisting...
Lecture 15: Projects Using Similar Data
What is an Array?An array is a data structure consisting of related data items of the same type.Stored in a group of memory locationsDefining arrays
int arrayName[ 100 ];
Examples int a[5]; float b[120], x[24];
……
a[0] 5
memory
10
15
3
23
a[1]
a[2]
a[3]a[4]
Specifying the type of each element
Name of the array
The number of the elements
Passing Arrays to FunctionsThe name of an array evaluates to the address of the first element of the array.Passing arrays
To pass an array argument to a function, specify the name of the array without any brackets
int anArray[100];aFunction( anArray, 100 );
Array size usually passed to functionFunction knows where the array is stored
Modifies original memory locations
Defining Function with Array ParametersThe function’s parameter list must specify that an array will be received.
void aFunction( int ary[ ], int size ) {
……..}
Function prototype void aFunction( int ary[ ], int size );
Parameter names optional in prototype int ary[ ] could be written int [] int size could be simply int
The header of the function
The size of the array is NOT required.
void aFunction( int [ ], int );
Defining Function with Array Parameters
Using the type qualifier const.void aFunction( const int ary[ ], int size )
The modification of the array elements are NOT allowed.
Any attempt to modify an element of the array in the function body results in a compile-time error.
The header of the function
Passing Array Elements
Passed by call-by-value.Array elements are like normal variables
Pass subscripted name to functionvoid modifyArrayElement( int arrayElement );
int array[ 10 ] = {0};
modifyArrayElement( array[1] );
modifyArrayElement( array[8] );
Practice Question
Q. Which is the right way to pass an integer array argument ary to the following function?
void func( int a[] );int ary[25];
A. func( ary[25] );B. func( ary[] );C. func( ary );D. func( ary[0] );
Solu
tion
: C
Practice Question
Q. Which is NOT the right way to pass an integer array argument ary to the following function?
#include<stdio.h>#define SIZE 5;void func( int a[], int x );int main( void ){int b[SIZE] = {1, 2, 3, 4, 5};
func(b, b[1]);printf(“%d %d\n”, b[0], b[1]);return 0;}
void func( int a[], int x){int k;for (k = 0; k < SIZE; k++) a[k] *= 2;x *= 2;}
A. 1 2B. 2 4C. 2 8D. 1 4
Solu
tion
: B