11 - C++ Arrays

Up till now, you have used variables to store a single value. C++ offers the flexibility to store multiple values of the same type, and address them with a single name. The mechanism that enables this is arrays.

An Array is a variable that allows you to store multiple values of the same type. Let’s say you need to store three integer values. You can either create three different integer variables or create an integer array that stores three values.  

11.1 Declaring Arrays

Similar to other variables, in C++, you need define an array before you can use it. Like other definitions, an array has a data type and a name. In addition, you need specify the size of an array. The size of an array is the no of values (data items) it will hold. It immediately follows the array name and is enclosed in square brackets “[]”.

Syntax for declaring an array is as follows:

       datatype arrayname[size];

Let’s say you want to create an array that holds 3 integer values; following is the definition:       

 int arr[3];

  In the above example, the name of the array is “arr”, its data type is integer and size is “3”. 

11.2 Array Elements 

Each value (data item) that an array holds is referred as an array element. All elements of an array are of the same data type. You can reference all the elements individually or together. Let’s create an array that stores the marks of three subjects:

        int marks[3];

  • The array name is “marks” and size of the array is 3. Thus, the array (marks) can hold three integer data items.
  • When the compiler comes across the above statement it sets aside memory for three integers.

11.3 Array Index

Each array element has an array index. You can use the array index to reference each element individually. You can think of an array as a set of boxes. Each box has a label and contains an article. The label on the box is the array index and the article in the box is the array element.

A pictorial representation of the above example is as follows:

               

For all arrays, the array index begins from zero. So if you want to reference the 2nd array element its array index would be “1” and not “2”. Similarly, the array index to reference the 3rd array element would be “2” (not 3).

Let’s create an array that holds three integers and print each array element on screen. The C++ statements to do so are as follows:     

1.    int arr[3]={12,24,36};
2.    cout<< arr[0]<<endl;
3.    cout<< arr[1]<<endl;
4.    cout<< arr[2]<< endl;

Understanding the C++ statements:

  • In the first statement, you create an integer array “arr” whose size is 3, that is; it can hold three integer values. You also initialize all three array elements
  • The second statement displays “12” - the first array element on the screen. Note that the array index of the first element is zero “arr[0]”
  • The third statement displays “24” - the second array element on the screen
  • The fourth statement displays “36” - the third array element on the screen

11.4 Accessing Elements of Arrays

You can access individual array elements using the array index. For all arrays, the array index starts from zero. The syntax for referencing an array element is as follows:

       arrayname[arrayindex];

Let’s declare and initialize an array that stores the marks of four subjects; the C++ statements are as follows:

       int marks[4]={10,20,30,40};

A pictorial representation of the above array is as follows:

Let’s say you want to print the values of individual array elements on the screen; the C++ statements to do so are as follows:  

cout<<marks[0]<<endl;
cout<<marks[1]<<endl;
cout<<marks[2]<<endl;
cout<<marks[3]<<endl;

The above statements will display the following values on the screen:

10

20

30

40

The array index begins from zero. The index of the last element (based on the above example is “3”) and not “4”; even though the array stores four integer values. Similarly, if you were to access the 2nd element its index would be marks[1] and not marks[2].

11.5 Initialising an Array 

Similar to other variables, you initialize arrays. When you initialize an array, you assign values to each array element. You can initialize array elements in the following ways:

  • Array Initializer List: Let’s say you have defined an array to store the marks of three subjects. When you initialize this array, you will specify the actual marks for each subject. The C++ statement to create and initialize the array is as follows:

            int marks[3]= {75,95,65};

The list of numbers enclosed in curly brackets “{}” to the right of “=” is known as an Array Initializer list.

  • Loop:  You can initialize array elements using a loop. This is useful when you have to initialize bigger arrays; for example, arrays that need to hold 100 or 1000 elements. To initialize bigger arrays, you can use an array initializer list too but it’s a tedious process. The C++ statements to initialize an array using a “for” loop are as follows:

 

1.    int marks[20];
2.    for(int x=0;x<20;<<x++)
3.    {
4.        marks[x]=100;
5.        cout<<”Element”<<x<<”:”<<”Value”<<marks[x]<<endl;
6.    } 

The output of the above program is as follows:          

       

Understanding the statements of the above example:

  • In the first statement, you declare an integer array named “marks” whose size is 10; that is, it can hold 10 integers. When the compiler comes across this statement, it sets aside memory for 10 integer data items.
  • In the next statement, you set the “for” loop to iterate 10 times and increment the value of “x” (loop variable) by one with each iteration
  • In the third statement, you initialize the value of each element to “100”. Thus, all array elements ( for the above example) will have the value of “100”

11.6 Multi-Dimensional Arrays

A multi-dimensional array contains other arrays. You can think of it as box that contains other smaller boxes in it. In this section, you will learn about two-dimensional array, which is a form of multi-dimensional array. A two-dimensional array is similar to a table or a grid. It contains two arrays; the first array is used to reference the rows and the second array the columns. Similar to a grid, you can access the elements of an array using the row and column coordinates.

The syntax for declaring a two-dimensional array is as follows:

        datatype arrayname[no of rows][no of columns];

Let’s look at an example of a two-dimensional array:       

        int newarr[2][3];  

In the above statement , you have declared an array “newarr”  that has two rows and three columns. Now, let’s initialize the elements of the array “newarr”:

      

Following is a diagrammatic representation of the above example:

     

The above array has two rows and three columns. Thus, it can hold six data items. Each array forms a separate row and each element forms a separate column.

11.7  Accessing Elements of Two-Dimensional Arrays

To access an element of a two-dimensional array, you need to specify which row the element is in, and then the column. Let’s look at the following table:


         

Let’s say you want to print the value “4”. The element is in the row “0”, and column “2”.  The C++ statement to print the element “4” is as follows:

      int newarr[2][3]={{2,3,4},{8,9,10}}; //declare and initialise array                 

      cout<<newarr[0][2]<<endl;                                       

Let’s say you want to print the data element “9”. Now, “9” is in the first row and first column (based on the above table). The C++ statement to print the element “9” on screen is as follows:

      cout<<newarr[1][1]<<endl;

11.8 Printing out Multi-Dimensional Array

To print out a multi-dimensional array on the screen you need to use loops. Let’s look at the following two-dimensional array:

     

The above table has two rows and each row has three columns. To print this table (two-dimensional array) on the screen, you need loop through each row (one by one). Next, loop through each column of that row. Let’s say you want to print the elements of the first row, in the above example, you will loop through the first row and every column of the first row.

11.9  C++ Example of Multi-Dimensional Arrays

The C++ statements to print the above two-dimensional array are as follows:

1.    #include<iostream.h>                    
2.    using namespace std;                    
3.    int main()                            
4.    {                                    
5.        int multiarr[2][3]={{1,2,3},{7,8,9}};          
6.        for(row=0;row<2;row++)                
7.        {                                
8.            for(column=0;column<3;column++)        
9.            {                            
10.            cout<<multiarr[row][column]<<” ”;  
11.        }                            
12.    cout<<endl;                        
13.    }                                
14.    } 

Understanding the statements of the above program:

  • In the 5th statement, of the above program, you create an array (“multiarr”) that has two rows and three columns and initialize the elements of the arrays. The multi-dimensional array “multiarr” contains two arrays - the first array represents the rows and the second array represents the elements of that row (columns).
  •  To print this array on screen (in a table/grid) format, you loop through each row one at a time and print the elements of that row (the row you are looping) on the screen. To do so, you need two “for” loops. The first one loops through each row (one at a time), and the second “for” loop is used to loop through each column of a row.
    • In the 6th statement, you declare a “for” loop for each row. The name of loop variable of the “for” loop is “row”. Its starting value is zero (as all arrays start from zero) and maximum value is two (the no of rows in your array). Each iteration, increments the value of the loop variable “row” by one.
    • Similarly, in the 8th statement, you declare a “for” loop for each column of a row. The name of loop variable of the “for” loop is “column”. Its starting value is zero (as all arrays start from zero) and maximum value is three (the no of columns in your array). Each iteration, increments the value of the loop variable “column” by one.
  • The “cout” statement, the 12th statement of the program, prints the values of each column (of the row you are looping). For example, if you looping through the row”0”, then the “cout” statement will print the values “1,2,3” on the screen (with each iteration of the “for” loop, which references the columns).
    • Let’s look at an example , where the value of row variable is set to “1” and that of the column variable is “0”
for (row=1, row<2; row++)
    {
        for(column=0; column<3;column++)
        {
            cout<< multarr[row][column]<<” “;
        }    
            
    }              

Based on above C++ statements, the “cout” will print the value “8” on the screen. This is because the coordinates of element “8” are row[1]and column[0]

  • In the 12th statement of the above program, you include a statement to start a new line (endl). This is done so that the elements (values) of each row are displayed on separate lines

Like us on Facebook