# Spiral Matrix in C/C++

Hello everyone, in this tutorial, I will guide you with the basic of filling up a Double-Dimension matrix, in spiral order in C or C++. In simple words, what the program does is ask for the number of elements the user wants, and creates a square matrix (* note: the matrix created needs to be a square). After which values are automatically stored to show you the ‘spirality’. After which the matrix is printed out with proper indentation.

### Circular Matrix (Spiral Matrix) in C/C++

#include<stdio.h> #include<conio.h> int main() { int inp; printf("Enter Dimension "); scanf("%d",&inp); int A[inp][inp]; int row1=0,col1=0,row2=inp-1,col2=inp-1,iter=1; while(iter<=(inp*inp)) { for(int i=col1;i<=col2;i++) {A[row1][i]=iter++;} for(int j=row1+1;j<=row2;j++) {A[j][col2]=iter++;} for(int i=col2-1;i>=col1;i--) { A[row2][i]=iter++; } for(int j=row2-1;j>=row1+1;j--) { A[j][col1]=iter++; } row1++;row2--;col1++;col2--; } printf("Two Dimensional array elements:\n"); for(int i=0; i<inp; i++) { for(int j=0;j<inp;j++) { printf("%d \t", A[i][j]); } printf("\n"); } return 0; }

Output :

Enter Dimension 5 Two Dimensional array elements: 1 2 3 4 5 16 17 18 19 6 15 24 25 20 7 14 23 22 21 8 13 12 11 10 9

#### Explanation: Spiral Matrix in C/C++

The program begins by importing the i/o libraries, after which the main is directly executed. We did not divide the program into methods, but the user can, if they wish to. The program begins by taking a (integer) dimension as an input, and initializing the double array dimension with it. The next step is initializing further variables, which depend on the dimension. The next part is the most important one; we use a while loop to run the program for a square of, boundary element. Inside which we issue for-loops.

- The first one begins by keeping the Row index constant and changing the Column index for every element. It runs from 0, to element dimension minus one times.
- The second one issues a fixed column index, and changing the row index with each iteration, it starts from row index of one and continues till element minus one.
- The third one is quite similar to the first one, but reverse in direction, so it begins from element minus one and continues till zero.
- The fourth one is again the opposite of second step, thus it begins from, dimension minus two since it is going inside the body.
- The last important step is to iterate ‘row1’ and ‘col1’, while decrementing ‘row2’ and ‘col2’.

After the completion of the loops, we print out the Double Dimension array with proper indentation.

You may also read:

## Leave a Reply

You must be logged in to post a comment.