Write a program to print the numbers in following pattern. 
1 2 3 
8 9 4 
7 6 5 

Input and Output Constraints: 
Input consists of an integer n which denotes the number of rows and columns. Input must be not more than 25. 
Output must consists of numbers from 1 to n*n printed in spiral pattern. 

Sample Input: 
Pattern is: 
1 2 3 
8 9 4 
7 6 5 

Sample Input: 
Pattern is:  
1 2 3 4 
12 13 14 5 
11 16 15 6 
10 9 8 7 

Program Code:
#include <stdio.h>
//#define SIZE 4 // Size is always even
int main()
{
int i, j, N,SIZE;
scanf("%d",&SIZE);
int board[SIZE][SIZE];
int left, top;
left = 0;
top  = SIZE - 1;
N   = 1;
for(i=1; i<=SIZE; i++, left++, top--)
{
// Fill from left to right
for(j=left; j<=top; j++, N++)
{
 board[left][j] = N;
}
 // Fill from top to down
for(j=left+1; j<=top; j++, N++)
{
board[j][top] = N;
}
 // Fill from right to left
for(j=top-1; j>=left; j--, N++)
{
board[top][j] = N;
}
// Fill from down to top
for(j=top-1; j>=left+1; j--, N++)
{
board[j][left] = N;
}
}
// Print the pattern
printf("PATTERN IS:\n");
for(i=0; i<SIZE; i++)
{
for(j=0; j<SIZE; j++)
{
printf("%d ", board[i][j]);
}
printf("\n");
}
return 0;
}
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: