An array is a data type in C/C++ used to hold sequence objects with the same data type.
Consider we have a string with multiple characters. How would we store and represent the string in our program? Here, we can initialize a char
array object in C/C++ with the string.
A 2D array is referred to as an array of arrays. Below is a diagram showing what 2D arrays are and how they are represented.
On the left side, we see an array represented by red. Each cell in the array contains another array represented on the right by the green color.
A 2D array can be imagined as a matrix with rows and columns where the rows represent the individual arrays, while the columns represent the elements of those arrays.
For example, if we want to retrieve the number 11 in our 2D array represented in the diagram, we would have to start with the row value, which is 2, and the column value, which is 1. We can access it using the index [2][1]
in our 2D array.
Below, we can see the syntax used to create a 2D array in C/C++:
dataType arrayName[int rowSize][int columnSize];
Below, we can see what these placeholders mean:
dataType
: The type of elements that we want to store in the array. The data type of the array should be the same as the elements.
rowSize
: The number of rows we want in our 2D array object, which represents arrays.
columnSize
: The number of elements that each array can contain.
Let's suppose we have to make a tic-tac-toe game in C/C++. We need a data object to store a 3x3 matrix representing the 9 boxes in a tic-tac-toe game.
Here, we can create a character array with 3 rows and 3 columns so our array declaration would look like the following line of code.
char ticTacToeTable[3][3];
Here, we will use the dataType
of char
since we have to store characters X and O as inputs to the 2D array.
Below, we can see a sample C application that shows how to create a 2D array named numbers of size 4x4 to store numbers and uses two for
loops to loop over the elements in the array and print them onto the console.
#include <stdio.h>int main() {int numbers[4][4] = { {1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16} };for(int i = 0; i < 4; i++){for(int j = 0; j < 4; j++){printf("numbers[%d][%d]: %d ", i, j, numbers[i][j]);}printf("\n");}}
Lines 4–7: We create and initialize a 2D int
array named numbers
with 4 rows and 4 columns.
Lines 9–14: We use two for
loops to print each element in the 2D numbers
array and format the output to display each array/row in one line.
Now that we have gone over 2D arrays in C/C++ and how we can perform array manipulation operations on the array, let's try to solve the practice questions below.
Below, we can see a char
array named tic_tac_toe
.
char tic_tac_toe = {{'X', 'O', 'X'}, {'X', 'X', 'O'}, {'O', 'O', 'X'}}
What would we get when we print tic_tac_toe[1][1]
?
X
O
Out of bounds!
Free Resources