Arrays As A Parameter
Arrays As A Parameter
ONE-DIMENSIONAL ARRAYS
A list of values with the same data type that are stored
using a single group name (array name).
General array declaration statement:
data-type array-name[number-of-items];
The number-of-items must be specified before declaring the
array.
const int SIZE = 100;
float arr[SIZE];
ONE-DIMENSIONAL ARRAYS (CONT.)
Individual elements of the array can be accessed by
specifying the name of the array and the element's index:
arr[3]
Warning: indices assume values from 0 to number-of-
items -1!!
ONE-DIMENSIONAL ARRAYS (CONT.)
element 3
Start here
1D ARRAY INITIALIZATION
Arrays can be initialized during their declaration
int arr[5] = {98, 87, 92, 79, 85};
int arr[5] = {98, 87} - what happens in this case??
What is the difference between the following two
declarations ?
char codes[] = {'s', 'a', 'm', 'p', 'l', 'e'};
char codes[] = "sample";
codes[0] codes[1] codes[2] codes[3] codes[4] codes[5] codes[6]
s a m p l e \0
TWO-DIMENSIONAL ARRAYS
void main()
{
const numRows = 2;
const numCols = 2;
int arr2D[numRows][numCols] = {2, 18, 1, 27};
float average;
avg=0.0;
for(i=0; i<n; i++)
for(j=0; j<m; j++)
avg += vals[i][j];
avg = avg/(n*m);
return avg;
}
2D ARRAYS AS ARGUMENTS (CONT.)
Important: this is essentially "call by reference":
a) The name of the array arr2D stores the address of arr2D[0]
(i.e., &arr2D[0])
b) arr2D[0] stores the address of the first element of the array
arr2D[0][0] (&arr2D[0][0])
c) Every other element of the array can be accessed by using its
indices as an offset from the first element.