Lesson 7: Arrays


Arrays

An array is a type of variable (or a collection of variables) that are accessed with an index number. Instead of containing a single value, an array can contain many values stored in separate elements. It is useful when we want to store similar data using only one variable.

 Array variable

Example:

int var1 = 5;
int var2 = 6;
int var3 = 7;
int var4 = 8;
int var5 = 9;

 

Can be replaced by declaring a 1-dimensional array with 5 elements:

int var[5];  // 1-dimensional array with 5 elements
var[0] = 5;  // set element 0 to be “5”
var[1] = 6;  // set element 1 to be “6”
var[2] = 7;  // set element 2 to be “7”
var[3] = 8;  // set element 3 to be “8”
var[4] = 9;  // set element 4 to be “9”

or

int var[] = {5, 6, 7, 8, 9 };

or

int var[5] = {5, 6, 7, 8, 9}

Arrays

Arrays allow you to group together similar data while referring to one variable name. The data in the variables are accessed by its index number.

 

 

Example 1:

int ledPin[] = {5, 6, 7, 8, 9};
for (int i = 5; i < 10; i++) {
   pinMode(ledPin[i], OUTPUT);
}

Example 2:

int ledPin[5];
int j = 3;

for (int i = 0; i < 5; i++) {
 ledPin[i] = j;
 j++;
}

What are the values of ledPin[0], ledPin[1], ledPin[2], ledPin[3] and ledPin[4] at this point?

Example 3:

int ledPin[5] = {5, 6, 7, 8, 9};

for (int i = 0; i < 5; i++) {
  digitalWrite(ledPin[i], HIGH);
  delay(100);
  digitalWrite(ledPin[i], LOW);
  delay(100);
}

In each of the above examples, we declared an array of type int. We can both declare and initialize the array, or just declare the array without initializing.

Arrays are zero-based, that is, the first element of the array is at index 0 (zero). For example, an array that has 10 (ten) elements, has index 9 (nine) as the last element in the array because we start at 0.

Note: Be careful when reading from your array. If you try to access an element that is greater than the declared size of your array, you are reading data from memory that is in use for other purposes.