\(\begin{array}{ccccc}1&2&3&4&5\\16&17&18&19&6\\15&24&25&20&7\\14&23&22&21&8\\13&12&11&10&9\end{array}\)
Write a program that reads a number and displays the above pattern.
Difficulty level
This exercise is mostly suitable for students
#include<stdio.h>
#include<conio.h>
#define SIZE 100
void main()
{
int N, i, j;
int grid[SIZE][SIZE];
int left, top, counter;
do{
printf("Enter N: ");
scanf("%d",&N);
}while(N<=0 || N>SIZE);
left = 0;
top = N - 1;
counter = 1;
// at each iteration, we will fill
// 1. the upper row (from left to right) -->
// 2. the right column (from top to bottom)
// 3. the lower row (from right to left) <--
// 4. the left column (from bottom to top)
// so basically, we will be looping N/2 times
// we take into account where N is odd, we need
// to add one more iteration
for(i=1; i<=N/2+1; i++, left++, top--)
{
// 1. fill the upper row (from left to right) -->
for(j=left; j<=top; j++, counter++)
grid[left][j] = counter;
// 2. fill the right column (from top to bottom)
for(j=left+1; j<=top; j++, counter++)
grid[j][top] = counter;
// 3. fill the lower row (from right to left) <--
for(j=top-1; j>=left; j--, counter++)
grid[top][j] = counter;
// 4. fill the left column (from bottom to top)
for(j=top-1; j>=left+1; j--, counter++)
grid[j][left] = counter;
}
for(i=0; i<N; i++)
{
for(j=0; j<N; j++)
printf("%4d", grid[i][j]);
printf("\n");
}
getch();
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Farthest point from the circle center