# Print Matrix in Spiral Order

Print Matrix in Spiral Order” is a standard interview problem based on matrix data structure which have been asked in many technical and algorithmic interviews.

Here, we are given a matrix of size N*M and our task is to print the following matrix in spiral Order.

Example:

```INPUT:
N=3, M=3
1  2  3
4  5  6
7  8  9
OUTPUT:
1 2 3 6 9 8 7 4 5
INPUT:
N=4, M=3
1  2  3
4  5  6
7  8  9
10 11 12
OUTPUT:
1 2 3 6 9 12 11 10 7 4 5 8
```

The steps required to Print Matrix in Spiral Order are as follows:

1. Four for loops will be used to print the matrix in spiral form:
2. First “for” loop will print row elements from left to right.
3. Second “for” loop will print column elements from top to bottom.
4. Third “for” loop will print row elements from right to left.
5. Fourth “for” loop will print column elements from bottom to top.

The following four “for” loops will work under the constraints of:

1.Starting row index.

2. Ending row index.

3. Starting column index.

4. Ending column index.

Initially, outer boundary elements will be printed, then constraints of point2 will be updated for inner boundary elements, in that way, the spiral printing will be done.

#### C++ Program to print Matrix in Spiral Order is as follows:

```/* Program to print Matrix in Spiral Order */
#include<bits/stdc++.h>
using namespace std;
int main()
{
// Scan Dimensions of the Matrix
int row,col;
cout<<"Enter the dimensions of the matrix:";
cin>>row>>col;

//Initialize a Matrix
int matrix[row][col];

//Scan The Matrix
cout<<"Enter the Elements of the matrix:";
for(int i = 0 ; i < row ; i++)
for(int j = 0 ; j < col ; j++)
cin>>matrix[i][j];

// Printing Matrix in Spiral Form
int startCol = 0;
int endCol=col-1;
int startRow=0;
int endRow=row-1;
int i,j;

cout<<"Matrix in Spiral Form is:\n";
while(startCol<=endCol&&startRow<=endRow)
{
// Print the first row
for(j=startCol;j<=endCol;j++)
{
cout<<matrix[startRow][j]<<" ";

}
startRow++;
// Print the last column
for(i=startRow;i<=endRow;i++)
{
cout<<matrix[i][endCol]<<" ";

}
endCol--;

if(startRow<=endRow)
{
// Print last Row, if exist
for(j=endCol;j>=startCol;j--)
{
cout<<matrix[endRow][j]<<" ";
}

}
endRow--;
if(startCol<=endCol)
{
// Print first col,if exist
for(i=endRow;i>=startRow;i--)
{
cout<<matrix[i][startCol]<<" ";
}
}
startCol++;
}
return 0;
}

```
```OUTPUT:
Enter the dimensions of the matrix: 4 4
Enter the Elements of the matrix:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Matrix in Spiral Form is:
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10```

Related Posts: