Professional Documents
Culture Documents
aggregating varabiles
Array Terms
aggregate construct – a construct that allows manipulation of multiple entities
as a single entity
array - a collection of variables called (array) elements or indexed variables
array is an aggregate construct
elements have two names
name of the array – the same for all elements of single array
index (or subscript) - different for element, put in square brackets []
example: array score may have following elements:
…, score[2], score[3], score[4], …
baseType id [ sizeExpession ] ;
array expression
base type specifies number
array of array elements
name
3
Array Usage
indexed variable can be used anywhere a scalar variable can be:
cin >> score[4] >> score[2];
max = score[4] + score[2];
score[4] = max;
cout << score[2] << ” ” << score[4];
4
Array with Loops Example
// finds minimum of array
int main(){
const int numNumbers=5;
int numbers[numNumbers]; // array of numbers
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9] myvar
6
Initializing Array
what is initialization again?
array elements can be initialized at once:
int a[10]={0, 10, 20, 30, 40, 50, 60, 70, 80, 90};
may skip array size at initialization (size computed to hold all values)
int a[]={10,20,30}; // array size is three
7
Arrays and Functions
array elements can be passed as arguments to functions:
int i=5, n, a[10];
myfunc(n); // scalar variable as argument
myfunc(a[3]); // element as argument
myfunc(a[i]); // which element is passed?
entire array can be passed as argument
always passed by reference (no & needed)
function does not know array size, it is usually passed as a separate variable
9
Review Questions
what is an aggregate construct?
what is an array?
what is name of the array? index?
what is indexed variable? element of the array? scalar variable?
what is array size?
what is array’s base type?
how is array declared?
what number do indexes start from?
what is out-of-range error? is it a syntax error or a bug?
how is array initialized?
can arrays be passed as arguments to functions? If yes by value or by
reference? If yes, how is size of array passed?
what does const mean in the following declaration?
void myfunc(const int []);
10