# PATTERN PRINTING – 29 (Spiral Pattern)

The pattern we need to print is in shape of square spiral (it starts with 1 at the top left corner and moves inwards increasing the count.) The figure above thus shows 1 at the top left corner and 25 at the centre.

The pattern can be thought as a 2-D matrix or a 2-D array. So we first represent the numbers in an 2-D array starting with (0,0) as shown in the figure below.

To store it in an 2-D array we need to traverse in an sprial or in loops. The traversal begins with the number 0 i.e. the outer loop is traversed first and then moving inwards. The figure below shows the traversals in different colors.

The above pattern requires total of 3 traversals.

– Firstly the red outer traversal.

– Then the second yellow and last the blue traversal.

**Logic for the code:**

– Firstly we take input of size of matrix(n).

– Number of traversals equals (round = n/2 Note: For n=5 ; traversals = 3 and for n=4 traversals = 2)

– Create a variable count=1

– For each traversal(i) (starting 0 till less than round)

– Store in array the upper row (from (i,i) to ((i, n-i-1) )) by incrementing the count.

– Store in array rightmost column (from (i+1, n-i-1) to (n-i-1, n-i-1) [We didn’t start from (i,n-i-1) since we need to move to the next row]) by incrementing the count.

– Store in array bottom row (from (n-i-1, n-i-1) to (n-i-1, i)) by incrementing the count.

– Store in array leftmost column(from (n-i-2, i) to (i+1, i)) by incrementing the count.

– Now we need to print the 2-D array.

#include<stdio.h> #include<math.h> int main(){ int arr[20][20],n,t,i,max=0,index,j; printf("Enter size of matrixn"); scanf("%d",&n); int count=1; // Number of traversals int round = ceil((double)n/2); // For each traversal for(i=0;i<round;i++){ // Topmost row for(j=i;j<=n-i-1;j++){ arr[i][j]=count++; } // Rightmost column for(j=i+1;j<=n-i-1;j++){ arr[j][n-i-1]=count++; } // Bottommost row for(j=n-i-2;j>=i;j--){ arr[n-i-1][j]=count++; } // Leftmost column for(j=n-i-2;j>i;j--){ arr[j][i]=count++; } } // Print array for(i=0;i<n;i++){ for(j=0;j<n;j++) printf("%d ",arr[i][j]); printf("n"); } return 0; }

Next Post: Pattern Printing 30

Category: Printing Pattern

Previous Post: Pattern Printing 28

can u please make any program or show tutorial in youtube using function pointers??

Thank u for all the videos tutorials you made.