To print numbers in an inverse spiral form
Question:
Write a program to generate an inverse spiral form using numbers.
Logic:
- Get the length of the spiral from the user.
- Then find starting index of the spiral.
- Print the top row and then print right column.
- Then print the bottom row and left column.
- It gives the inverse spiral like structure.
Algorithm:
- Get the spiral length from the user.
- Find the starting index of the spiral in the array.
- By incrementing the count value for each position gives the spiral structure.
- Then store count value to the top row and then the right column in the array.
- And then store to the bottom row and the left column of the array
Program:
#include<stdio.h> void main() { int n,a,b[20][20],count=1,i,j,d,c; clrscr(); printf("enter number of rows:"); scanf("%d",&n); c=n; //n value stroes in another variable to print pattern a=n/2; //determines the starting position of pattern d=n*n; //end value of count if(n%2==0) { a=a-1; n=n-1; } for(i=0;a>=0;i++) { for(j=a;j<=n-a&&count<=d;j++) //stores the upper row { b[a][j]=count++; } for(j=a+1;j<=n-a&&count<=d;j++) //stores the right column { b[j][n-a]=count++; } for(j=n-a-1;j>=a-1&&count<=d;j--) //stores the lower row { b[n-a][j]=count++; } for(j=n-a-1;j>a-1&&count<=d;j--) //stores the left column { b[j][a-1]=count++; } a--; } for(i=0;i<c;i++) //prints the overall pattern { for(j=0;j<c;j++) { printf("%3d",b[i][j]); } printf("\n"); } getch(); }