1-dimensional arrays
C provides support for 1-dimensional arrays
by allowing us to identify the required data using a single index
into the array.
Syntactically, we use square-brackets to identify that the variable is an
array, and use an integer expression
inside the array to identify which "part" of it we're requiring.
In all cases, an array is only a single variable,
with one or more elements.
Consider the following code:
#define N 20
int myarray[ N ];
int evensum;
evensum = 0;
for(int i=0 ; i < N ; ++i) {
myarray[ i ] = i * 2;
evensum = evensum + myarray[ i ];
}
|
|
What do we learn from this example?
- We declare our 1-dimensional arrays with square brackets,
and indicate the maximum number of elements within those brackets.
- A fixed, known value (here N, with the value 20)
is used to specify the number of elements of the array.
- We access elements of the array by providing the array's name,
and an integer index into the array.
- Elements of an array may be used in the same contexts as basic
(scalar) variables.
Here myarray is used on both the left-hand and right-hand sides of
assignment statements.
We may also pass array elements as arguments to functions,
and return their values from functions.
- Array indicies start "counting" from 0 (not from 1).
- Because our array consists of N integers,
and indicies begin at zero,
the highest valid index is actually N-1.
|
CITS2002 Systems Programming, Lecture 6, p2, 8th August 2023.
|