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:
- Get the input length from the user.
- Find the two-dimensional array size for storing values.
- Count value stores into an array by incrementing its value for every position.
- It stores in order top, right, bottom and right.
- 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(); }