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// Copyright (c) 2020 Mr. Coxall All rights reserved.
 2//
 3// Created by: Mr. Coxall
 4// Created on: Sep 2020
 5// This program uses a 2D array as a parameter
 6
 7#include <stdio.h>
 8#include <stdlib.h>
 9#include <time.h>
10
11// in C you must pass in the size of the 2D array to a function, first
12int sumOfNumbers(int rows, int columns, int arrayOfNumbers[rows][columns]) {
13    // this function adds up all of the numbers in a 2D array
14
15    int total = 0;
16
17    // loop through 2D array and add all numbers together
18    for (int rowCounter = 0; rowCounter < rows; rowCounter++) {
19        for (int columnCounter = 0; columnCounter < columns; columnCounter++) {
20            total += arrayOfNumbers[rowCounter][columnCounter];
21        }
22    }
23
24    return total;
25}
26
27int main() {
28    // this function uses a 2D array
29    const int rows = 7;
30    const int columns = 5;
31    int number2DArray[rows][columns];
32    int seed = time(NULL);
33
34    // input
35    srand(seed);
36    // Generate random numbers and populate the 2D array
37    for (int row = 0; row < rows; row++) {
38        for (int column = 0; column < columns; column++) {
39            int aRandomNumber = rand() % 9;
40            number2DArray[row][column] = aRandomNumber;
41            printf("%d ", aRandomNumber);
42        }
43        printf("\n");
44    }
45    printf("\n");
46
47    // call function
48    int sumNumbers = sumOfNumbers(rows, columns, number2DArray);
49
50    // output
51    printf("The sum of all the numbers is: %d\n", sumNumbers);
52
53    printf("\nDone.\n");
54    return 0;
55}

Example Output

Code example output