1 2 3 4 5 620 21 22 23 24 719 32 33 34 25 818 31 36 35 26 917 30 29 28 27 1016 15 14 13 12 11
1 2 3 4 5 6 7 8 9 10 36 37 38 39 40 41 42 43 44 11 35 64 65 66 67 68 69 70 45 12 34 63 84 85 86 87 88 71 46 13 33 62 83 96 97 98 89 72 47 14 32 61 82 95 100 99 90 73 48 15 31 60 81 94 93 92 91 74 49 16 30 59 80 79 78 77 76 75 50 17 29 58 57 56 55 54 53 52 51 18 28 27 26 25 24 23 22 21 20 19
/**
* C program to print perfect square number pattern
*/
#include <stdio.h>
#define SIZE 6 // Size is always even
int main()
{
int i, j, N;
int board[SIZE][SIZE];
int left, top;
left = 0;
top = SIZE - 1;
N = 1;
for(i=1; i<=SIZE/2; 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
for(i=0; i<SIZE; i++)
{
for(j=0; j<SIZE; j++)
{
printf("%-5d", board[i][j]);
}
printf("\n");
}
return 0;
}
1 2 3 4 5 6 7 8 9 10
36 37 38 39 40 41 42 43 44 11
35 64 65 66 67 68 69 70 45 12
34 63 84 85 86 87 88 71 46 13
33 62 83 96 97 98 89 72 47 14
32 61 82 95 100 99 90 73 48 15
31 60 81 94 93 92 91 74 49 16
30 59 80 79 78 77 76 75 50 17
29 58 57 56 55 54 53 52 51 18
28 27 26 25 24 23 22 21 20 19
Required knowledge:
Basic C programming , Loop , Array
Note: If you want to generate the perfect square of any number other than 10. Then you only need to change this line #define SIZE 10 to any other integer.
First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.