Robotics C++ Physics II AP Physics B Electronics Java Astronomy Other Courses Summer Session  

Two Dimensional Arrays

 

 

Introduction

Initializing

Printing the Rows

Exercises

Prototypes, Etc.

Passing

Knight's Tour (one version)

Eight Queens

 

Introduction

 

Two-D array named arrayB

 

How cells are referred to using subscript or index notation

 

arrayB[0][0]

arrayB[0][1]

arrayB[0][2]

arrayB[0][3]

arrayB[1][0]

arrayB[1][1]

arrayB[1][2]

arrayB[1][3]

arrayB[2][0]

arrayB[2][1]

arrayB[2][2]

arrayB[2][3]


Horizontal elements beginning with cell identified as arrayB[0][0] are in row 1

Vertical elements beginning with cell identified as arrayB[0][1] are in column 2

This array is referred to as a 3x4 array (3 rows and 4 columns)

When listing subscripts or indices the row is given first followed by the column

Rows are in a horizontal line, columns are in a vertical line

 

Contents of cells

 

4

5

8

-3

2

9

1

5

6

7

21

14

 

The contents of the cells in row 1 are 4, 5, 8, -3

The contents of cells in column 4 are -3, 5, 14

The cell whose subscripts are 1, 2 (arrayB[1][2] ) holds the value 1

 

 

Initializing

 
 int b[2][2] = {{1,2}, {3,4}}
 
The values are grouped by row in braces. So,
 
1 and 2 initialize b[0][0] and b[0][1]
3 and 4 initialize b[1][0] and b[1][1]
 
If there are not enough initializers for a given row, the remaining elements of that row are initialized to 0.
If braces are removed, the compiler automatically initializes first row, then second, etc.
 
Double- subscripted arrays can also be initialized with loops as we did with single-subscripted.
 
#include <iostream>

using namespace std;


int main()
{
    int b[2][2] = {{1,2}, {3,4}};

    for (int i = 0; i < 2; i++)
        for (int j = 0; j < 2; j++)
            cout << b[i][j]<<endl;
    return 0;
}

 

 

 

Example: Printing Rows

           
#include <iostream>

using namespace std;


int main()
{
    int i, j;

    int array1[ 2 ][ 3 ] = { { 1, 2, 3 }, { 4, 5, 6 } },
    array2[ 2 ][ 3 ] = { 1, 2, 3, 4, 5 },
    array3[ 2 ][ 3 ] = { { 1, 2 }, { 4 } };

    cout << "Values in array1 by row are:" << endl;

    for ( i = 0; i < 2; i++ )
    {
    for ( j = 0; j < 3; j++ )
        cout << array1[ i ][ j ] << "";

    cout << endl;
    }

    cout << "Values in array2 by row are: " << endl;

    for (i = 0; i < 2; i++ )
    {
        for (j = 0; j < 3; j++ )
            cout << array2[ i ][ j ] << "";

        cout << endl;
    }

    cout << "Values in array3 by row are: " << endl;

    for ( i = 0; i < 2; i++ )
    {

        for ( j = 0; j < 3; j++ )
            cout << array3[ i ][ j ] << "";
        cout << endl;
    }
    return 0;
}