Sunday, 19 August 2012

C++ Programming Tutorial Lesson #6 - Arrays

What is an array?

An array is a group of variables that uses one name instead of many. To access each of the individual variables you use a number.

How to use an array

To declare an array put square brackets after the name of the array. These square brackets must have the number of variables or elements inside them. Here is an example of how to declare an array of integers which has 3 elements
int arr[3];
You can set the values of an array by using the number of the element you want to set in the square brackets behind it. Array elements start from 0 and not 1.
int arr[3];
arr[0] = 5;
arr[1] = 7;
arr[2] = 3;
Here is a table that shows you what the array looks like.

2D arrays

A 2D array is an array that has both rows and columns. You must use 2 sets of square brackets when declaring a 2D array and when using it.
int arr[3][3];
arr[0][0] = 5;
Here is a table that shows you what a 2D array looks like.

Using arrays with loops

Arrays appear to be nothing more than normal variables until you use them with loops. You can initialize all the elements of an array to 0 using a loop instead of setting them each individually.
int arr[3];
for (int x=0; x<3; x++)
   arr[x] = 0;
When you do this with a 2D array you need to use 2 loops.
int arr[3][3];
for (int x=0; x<3; x++)
   for (int y=0; y<3; y++)
      arr[x][y] = 0;