CSCI 150, Spring 2003

Home | | Course Schedule | | Assignments | | Lecture Notes

Arrays

Definition:
An array is a collection of individual values of the same data type stored in adjacent memory locations.

Here is an array of integers:

Referring to elements of the array:
The position of an element in an array is given by the index. The name of the array, followed by the index is used to refer to a particular element:

The above statement assigns the value 5 to the 2nd element of the array, myArray.

Declaring and array: Arrays are declared by first creating a type that refers to an array of some length and data type. The array is then declared as a variable of the array type:

Using elements of an array:
Elements of the array can be used in the same way as variables of the same data type can be used. I.e. an element of an array of integers can be used anywhere an integer variable can be used.

Using arrays with for loops.
Arrays go naturally with for loops as illustrated in the following examples:

1) Assigning values to each element of the array:

2) Reading in values for each element of an array:

3) Finding the sum of elements in an array:

4) Finding the minimum value of elements in an array: