To print numbers in spiral form

To print numbers in spiral form

This program can able to print the numbers in spiral form.

Logic:

  • Get the input length from the user.
  • Then stores the count value into the array by incrementing the count.
  • Stores into top row and then right column.
  • Then stores into bottom row and into the left column.
  • Prints the spiral stored in the array.

Algorithm:

  1. Get the input length from the user.
  2. Find the two-dimensional array size for storing values.
  3. Count value stores into an array by incrementing its value for every position.
  4. It stores in order top, right, bottom and right.
  5. Then prints the stored values.

Program:

#include<stdio.h>
void main()
{
	int i,j,b,n,count=1,a[20][20],c;
	clrscr();
	printf("enter the rows you want to print:");
	scanf("%d",&n);
	c=n*n;//calculate the length of matrix or array
	b=n/2;
	if(n%2!=0)
	{
		b=b+1;
	}
	for(i=0;i<=b&&count<c+1;i++)
	{
		for(j=i;j<=n-(i+1);j++)//stores in top row
		{
			a[i][j]=count++;
		}
		for(j=i+1;j<=n-(i+1);j++)//stores in right column
		{
			a[j][n-(i+1)]=count++;
		}
		for(j=n-(i+2);j>=i;j--)//stores in bottom row
		{
			a[n-(i+1)][j]=count++;
		}
		for(j=n-(i+2);j>i;j--)//stores in left column
		{
			a[j][i]=count++;
		}
	}
	for(i=0;i<n;i++)//prints the spiral
	{
		for(j=0;j<n;j++)
		{
			printf("%3d",a[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.
4.7 3 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