2-D Arrays in C++

This informative guide provides a deep look into 2-D arrays (also known as matrices) in c++. It provides a look at the concept and the need for 2-D arrays in c++. Highlighting the pros and cons of 2-D arrays. The text also provides code examples to help you learn how to create a 2-D array. And access its elements individually in c++, and allocate dynamic memory for a c++ 2-D array.

What is a 2-D array in c++?

Simply put, a 2-D array is a 2-Dimensional array. But what does 2-Dimensional mean?

2-Dimensional implies that the array is represented as an array of arrays. An array is a structure of data placed in a slot of persistent memory where each value has its own index. This structure is also known as a matrix. The data in an array is always homogeneous. Homogeneous meaning that all elements inside the array are of the same data type, i.e., integer, float, char, and more.

Why do we need 2-D arrays?

The usage of individual variables for storing values or objects is efficient when working with a small number of values. However, when dealing with a large number of values in c++, we need a proper arrangement. We implement an array or a 2-D array for representing extensive data in a tabular form.

A 2-D array is used in image and speech processing in programming concepts. Each row of the structure represents a single speech signal or image. 2-D arrays are also used as a map with horizontal and vertical reference points for visual environments of games.

How to create a 2-D array in c++?

A 2-D structure, i.e., an array of arrays, is designed as a matrix of rows and columns. Here, the rows and columns represent the index of any element and the total number of elements present in the matrix.

An element X in the array can be found by its row and column index represented by X[row][col], and the product of rows X columns gives the total elements inside the array.

You use the syntax, dataType arrayName[row][col]; in c++ to declare a 2-D array. Let us see how:

#include<iostream>
using namespace std;
int main()
{   
   //Declaring rows and columns
int rows = 4;
int cols = 4;
   
int myArray[rows][cols] = {{10,20,30,40}, {50,60,70,80}, {90,100,110,120}, {130,140,150,160}}; //Defining myArray elements

for (int r = 0; r < rows; r++)//Outer loop for rows
{
   for (int c = 0; c < cols; c++)//inner loop for columns
   {
    cout << myArray[r][c] << "\t";// print each element and provide spaces
   }
cout<<endl;// change line after a row is printed
}
return 0;
}

Output:

10      20      30      40
50      60      70      80
90      100     110     120
130     140     150     160

Here, we have the main function where we define a static array, i.e., an array with its number of rows and columns fixed. We take myArray of size 4×4 and put elements into it using curly parenthesis for defining each row of elements. Then we use a nested for loop for iterating and printing the elements of the 2-D array using cout. You can also use the cin object for getting the values of the 2-D array during run time.

Accessing individual elements inside a 2-D array

Generally, a for loop is used for iterating the whole 2-D array in c++. But you can also get the value of individual elements by using their indexed location inside the 2-D array, i.e., by providing their row and column index.

Let us show you how:

#include<iostream>
using namespace std;
int main()
{   
   //Declaring rows and columns
int rows = 4;
int cols = 4;

int myArray[rows][cols] = {{10,20,30,40}, {50,60,70,80}, {90,100,110,120}, {130,140,150,160}};

cout<<"Element at 0,0: "<<myArray[0][0] <<endl;
cout<<"Element at 1,1: "<<myArray[1][1] <<endl;

cout<<endl;

int R,C;

//Getting row and col value from user
cout<<"Enter row index: ";
cin>>R;

cout<<"Enter column index: ";
cin>>C;

//Displaying individual element
cout<<"Element: "<<myArray[R][C] <<endl;

return 0;
}

Output:

Element at 0,0: 10
Element at 1,1: 60

Enter row index: 3
Enter column index: 3
Element: 160

The above code snippet is a slight modification of the previous example. Instead of printing all the elements of the matrix, we use the cout method to print individual elements using their row and column index. We also use the cin method for inputting the row and column index for an element. And then printing its value using cout.

How to allocate memory for a c++ 2-D array dynamically

You can also allocate memory for a c++ 2-D array dynamically using a pointer. A c++ pointer is a particular variable used for storing the address of another variable. In this case, our 2-D array elements in c++.

Here, we take the number of rows and columns of the array and reserve a memory block in the memory. The data in the 2-D array is both saved and printed using the pointer.

#include <iostream>
using namespace std;

int main()
{
	// Declaring rows and columns
	int rows = 4, cols = 4;
	
	int x = 100;

	// Declaring pt pointer for memory of size rows*columns
	int* pt = new int[rows * cols];

	for (int r = 0; r < rows; r++) 
	{
		for (int c = 0; c < cols; c++) 
		{
			//Each element of the block gets incremented value of x
			*(pt + r * cols + c) = ++x;
		}
	}


	for (int r = 0; r < rows; r++) 
	{
		for (int c = 0; c < cols; c++) 
		{
			//printing values from the memory block
			cout << *(pt + r * cols + c) << " ";
		}
		cout << endl;//change line
	}
	
	cout << "Individual element at 2,2:  " << *(pt + 2 * cols + 2) << " ";
	
	delete[] pt;

	return 0;
}

Output:

101 102 103 104
105 106 107 108
109 110 111 112
113 114 115 116
Individual element at 2,2:  111

In the above code snippet, we define the number of rows and columns. We have taken a variable x that will increment each time to provide a new value at each position inside the c++ 2-D array.

We declare a pointer pt that will claim a memory block equal to the size of the 2-D array. Like the previous program, we use a nested for loops, one for rows, and one for columns, then use the pointer pt to get its value from variable x. Then we use another for loop to print the values of our 2-D array in c++.

The delete operator is used for deallocating the memory of the array from the heap. This will destroy the dynamic memory block we created to store our c++ 2-D array values.

Pros and Cons of 2-D Arrays in c++

Advantages:

  • You can represent various data items belonging to the same data type using a single structure or 2-D array for tabular form.
  • You can use a c++ 2-D array to implement linked lists, stacks, trees, and other complex data structures.
  • Matrix problems such as horizontal wave traversals, spiral matrices, magic matrices, and other complex programming logics are only possible using 2-D arrays.

Disadvantages:

  • Static 2-D array in c++ requires pre-known knowledge of the length and size of the data.
  • An array is saved as a slot, i.e., in continuous memory blocks, which is why insertion, deletion, or updating operations lead to significant problems and take time.
  • Once a 2-D array is created, you can only store similar data inside it as it is homogeneous. Moreover, unused elements will lead to a wastage of space as the full array will be stored in the memory when only specific values would be used.

Conclusion

You now know everything about 2-D arrays in c++. You have learned the basic syntax and creation of a c++ 2-D array and understand where 2-D arrays are used in programming applications. Furthermore, you also know about the dynamic allocation of memory using a pointer for a 2-D array in c++. You can list the advantages and disadvantages of using 2-D arrays in c++ and can implement them correctly according to your code’s requirements. It would be best to practice the concept learned in this article to brush up on your coding skills.

Please keep checking in for more informative guides on our website. You can also join our live classes for Python Programming, Data Analytics, and SQL via our skill enhancement program.

Good Luck with your coding!

Leave a Reply