To print numbers in an inverse spiral form

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:

  1. Get the spiral length from the user.
  2. Find the starting index of the spiral in the array.
  3. By incrementing the count value for each position gives the spiral structure.
  4. Then store count value to the top row and then the right column in the array.
  5. 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();
}

Follow For Instant Updates

Join WhatsApp Group: link
Join our Telegram Channel: link
Like our Facebook Page:  link
Subscribe to our Youtube channel: link

Vignesh

A Computer Science graduate who likes to make things simpler. When he’s not working, you can find him surfing the web, learning facts, tricks and life hacks. He also enjoys movies in his leisure time.
0 0 votes
Article Rating
Subscribe
Notify of
guest
5.4K Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
5.4K
0
Would love your thoughts, please comment.x
()
x