2D Arrays

All the arrays that we have used thus far have been to represent a collection of information. This is a very powerful tool and can save the programmer a lot of time and confusion when dealing with items that are somehow related to each other. Not all things can be represented with a single collection though. Several times we use a grid or spreadsheet to keep information in rows and columns. This matrix of information can not be represented in a single array. In these situations we represent our data with a 2-dimensional (or multi-dimensional array ).

A 2-D array can just be thought of an array of arrays.

2D-array

We represent a given element with 2 indices now, instead of 1 when we had a single dimension. Unlike in math class where you used the Cartesian plane, and moved in the X direction and then the Y direction,

Cartesian-coordinate-system

in computer science you move up and down in the rows first and then across to the column position. Thus if we want to refer to the element in the above array that has a value of 8, we would say, studentMarks(2, 1).

There are many applications of 2-D arrays, like a game board (tic-tac-toe), adventure games and business applications like spreadsheets.

Code for Creating and using a 2D Array

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// Copyright (c) 2020 Mr. Coxall All rights reserved.
//
// Created by: Mr. Coxall
// Created on: Sep 2020
// This program uses a 2D array as a parameter

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

// in C you must pass in the size of the 2D array to a function, first
int sumOfNumbers(int rows, int columns, int arrayOfNumbers[rows][columns]) {
    // this function adds up all of the numbers in a 2D array

    int total = 0;

    // loop through 2D array and add all numbers together
    for (int rowCounter = 0; rowCounter < rows; rowCounter++) {
        for (int columnCounter = 0; columnCounter < columns; columnCounter++) {
            total += arrayOfNumbers[rowCounter][columnCounter];
        }
    }

    return total;
}

int main() {
    // this function uses a 2D array
    const int rows = 7;
    const int columns = 5;
    int number2DArray[rows][columns];
    int seed = time(NULL);

    // input
    srand(seed);
    // Generate random numbers and populate the 2D array
    for (int row = 0; row < rows; row++) {
        for (int column = 0; column < columns; column++) {
            int aRandomNumber = rand() % 9;
            number2DArray[row][column] = aRandomNumber;
            printf("%d ", aRandomNumber);
        }
        printf("\n");
    }
    printf("\n");

    // call function
    int sumNumbers = sumOfNumbers(rows, columns, number2DArray);

    // output
    printf("The sum of all the numbers is: %d\n", sumNumbers);

    printf("\nDone.\n");
    return 0;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// Copyright (c) 2020 Mr. Coxall All rights reserved.
//
// Created by: Mr. Coxall
// Created on: Sep 2020
// This program uses a 2D array as a parameter

#include <iostream>
#include <cstdlib>
#include <ctime>


// In C++, a 2D array is passed by reference to a function
// (template is used to find the length of the array)
template <int rows, int cols>
int sumOfNumbers(int (&passedIn2DArray)[rows][cols]) {
    // this function adds up all of the numbers in a 2D array

    int total = 0;
    int counter = 0;

    //adding up all of the numbers in a 2D array
    for (int rowCounter = 0; rowCounter < rows; rowCounter++) {
        for (int columnCounter = 0; columnCounter < cols; columnCounter++) {
            total += passedIn2DArray[rowCounter][columnCounter];
        }
    }

    return total;
}

int main() {
    // this function uses a 2D array
    const int rows = 3;
    const int columns = 5;
    int a2DArray[rows][columns];
    int aSingleRandomNumber = 0;
    int sum = 0;

    srand(time(NULL));

    // input

    // So, ...
    //   In C++ you can't define array's size using variable.
    //   this is why you see const int rows = 2; above,
    //   so the size of the array can never change

    for (int rowElement = 0; rowElement < rows; rowElement++) {
        for (int columnElement = 0; columnElement < columns; columnElement++) {
            aSingleRandomNumber = (rand() % 9) + 1;
            a2DArray[rowElement][columnElement] = aSingleRandomNumber;
            std::cout << aSingleRandomNumber << " ";
        }
        std::cout << std::endl;
    }

    // call functions
    sum = sumOfNumbers(a2DArray);

    // output
    std::cout << "The sum of all the numbers is: " << sum << std::endl;

    std::cout << "\nDone." << std::endl;
    return 0;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Copyright (c) 2020 St. Mother Teresa HS All rights reserved.
//
// Created by: Mr. Coxall
// Created on: Sep 2020
// This program uses a 2D array

using System;

class Program
{
  static int SumOfNumbers(int[,] arrayOfNumbers)
  {
    // This function adds up all of the numbers in a 2D array

    int total = 0;
    int rows = arrayOfNumbers.GetLength(0);
    int columns = arrayOfNumbers.GetLength(1);

    // Loop through 2D array and add all numbers together
    for (int rowCounter = 0; rowCounter < rows; rowCounter++) {
      for (int columnCounter = 0; columnCounter < columns; columnCounter++) {
        total += arrayOfNumbers[rowCounter, columnCounter];
      }
    }

    return total;
  }

  static void Main()
  {
    // This function uses a 2D array
    const int rows = 7;
    const int columns = 5;
    int[,] number2DArray = new int[rows, columns];
    Random random = new Random();

    // Generate random numbers and populate the 2D array
    for (int row = 0; row < rows; row++)
    {
      for (int column = 0; column < columns; column++)
      {
        int aRandomNumber = random.Next(10);
        number2DArray[row, column] = aRandomNumber;
        Console.Write($"{aRandomNumber} ");
      }
      Console.WriteLine();
    }
    Console.WriteLine();

    // Call function
    int sumNumbers = SumOfNumbers(number2DArray);

    // Output
    Console.WriteLine($"The sum of all the numbers is: {sumNumbers}");

    Console.WriteLine("\nDone.");
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#!/usr/bin/env python3
"""
Created by: Mr. Coxall
Created on: Sep 2020
This module uses an array as a parameter
"""


import random
from typing import List


# in python an array is passed by reference to a function
def sum_of_numbers(array_of_numbers: List[List[int]]) -> int:
    """The sum_of_numbers() function calculates the sum of numbers in a 2D list, returns the sum as int."""

    total = 0

    for row_value in array_of_numbers:
        for single_value in row_value:
            total += single_value

    return total


def main() -> None:
    """The main() function just calls other functions, returns None."""

    a_2d_list = []
    sum_answer = 0

    # input
    rows = int(input("How many row would you like: "))
    columns = int(input("How many columns would you like: "))

    for _ in range(0, rows):
        temp_column = []
        for _ in range(0, columns):
            a_random_number = random.randint(0, 9)
            temp_column.append(a_random_number)
            print(f"{a_random_number} ", end="")
        a_2d_list.append(temp_column)
        print("")

    sum_answer = sum_of_numbers(a_2d_list)

    # output
    print(f"\nThe sum of all the numbers is: {sum_answer}")

    print("\nDone.")


if __name__ == "__main__":
    main()

Example Output

Code example output