# Program to reverse a Two Dimensional Array using C++

In this tutorial, we will focus on how to reverse a 2D array in C++.

Matrix is an inevitable part of mathematics. It is used in many statistical as well data storage systems. Simplicity and use of less storage space make matrices a good medium to of storing information.

## How to reverse a 2D array in C++

If the data stored is in the form of matrices, it is necessary to modify the contents of the matrices. Manipulation in the contents of the matrix will result in modification of the data.

### The Libraries included

```#include<iostream.h>
#include<conio.h>```

There are only two libraries included in this program. <iostream.h> and <conio.h> for input and output operations.

The main() program

Let’s divide the program into two parts for convenience.

#### Part 1:

```void main()
{
clrscr();
int a[i][j],i,j;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
cout<<"Enter Number";
cin>>a[i][j];
}
}

```

In this part, first we use clrscr() function to clear the screen before executing program. Then a two dimensional array is initialized, the two dimensions of the array ‘a’ are ‘i’ and ‘j’ written within square parenthesis.

Later, a ‘for’ loop is initialized with the conditions for ‘j’ within a ‘for’ loop of variable ‘i’. The basic algorithm of these ‘for’ loops is to take inputs for a, a, a, a and so on…

First, the value of ‘i’ will be set to 1 and values of ‘j’ will be set to 0,1 and 2 simultaneously. After exiting the ‘for’ loop of variable ‘j’, The value of ‘i’ will be incremented to 1 and the same procedure of ‘j’ loop will occur.

With this, a 3×3 matrix will be formed. If a smaller or a bigger matrix is to be used, the final values of ‘i’ and ‘j’ in the for loop must be modified.

#### Part 2:

```for(i=2;i>=0;i--)
{
for(j=2;j>=0;j--)
{
cout<<a[i][j]<<"\t";
}
cout<<endl;
}
getch();
}```

In this part, two ‘for’ loops are initialized in the same fashion. In these ‘for’ loops, the variables of the array which were added in the previous step are displayed in the exact reverse form, the variable stored first becomes the last term of the matrix whereas the last term becomes the first term.

For this to happen, the terms ‘i’ and ‘j’ are initialized as 2 and decremented till they become equal to zero, using ‘for’ loop. And single array terms are displayed simultaneously. The ‘tab’ command is used to add space between each term of the matrix.

Then, in the ‘i’ ‘for’ loop a command ‘endl’ is used to end the line and switch to the next to make the array look like a matrix.

Further, getch() is used to hold on the console screen until the whole program is executed.

#### Example:(Output)

```Enter the number
1
Enter the number
2
Enter the number
3
Enter the number
4
Enter the number
5
Enter the number
6
Enter the number
7
Enter the number
8
Enter the number
9
9   8   7
6   5   4
3   2   1```

This is how we reverse a 2D array in C++.

You may also read: