Suppose you had the phone numbers (for example: 9056679893, which is (905)667-9893) of all of the students in the school. Then suppose that you wanted to store this information in a C++ program you were writing. It would be very inefficient to have 2,500 variables declared to store all of those numbers:
int phone1 = 9056439087
int phone2 = 9052112345
int phone3 = 9056897843
. . .
int phone2449 = 9053456543
int phone2500 = 9052721112
After all, you probably don’t want to have to access each one separately. What you want is all of the phone numbers stored together in a group. To do this, we have a special construct called an array.
Arrays are a way of storing data that is of the same type. The array is an object that made up of compartments to store pieces of data. All of the pieces are groups together so we only need to name and declare them once. Because an array is an object, it needs to be constructed.
To declare an array:
int myarray[] = new int[5];
►
a picture of an array
You can also store all other data types, eg. char, float, objects inside your array.
To put things into your array when you declare it:
int myarray [5] = {66, 33, 1, 0, 7};
This would create an array like this:
►
the array after initializing
Note that on computers we always start numbering at the first number, which is zero. Therefore, in this example, 66 is in place 0, 33 in place 1, 1 in place 2, 0 in place 3 and 7 in place 4. 66 can also be referred to as the ‘zeroth’ element of the array. To a compartment of an array, you would use the following code:
myarray [2] = 104;
That puts 104 into the second element of the array. Our array would then look like:
►
the array after the change
One of the most useful things about arrays is that we can use for loops to go through them quickly:
for (int i=0; i<5; i++)
System.out.println(myarray[i]);
would print out: 66 33 104 0 7.
A style note for declaring arrays is that you should declare the size of the array as a variable and then use the variable in referencing the array in the future. Then, if you decide to change the size of the array, you only need to change it in one spot. For example:
int size =6;
int myarray [] = new int[size];
//for loop to set everything to be zero
for (int i = 0; i < size; i++)
{ myarray[i]=0; }
Here is a summary of array terms: