C Programming Code Examples C > Games and Graphics Code Examples Program to Solve the Magic Squares Puzzle without using Recursion Program to Solve the Magic Squares Puzzle without using Recursion The following C program, using iteration, finds the magic square for a given odd sized number. A magic square is an arrangement of numbers from 1 to n^2 in an [n x n] matrix, with each number occurring exactly once, and such that the sum of the entries of any row, any column, or any main diagonal is the same. #include <stdio.h> void magicsq(int, int [][10]); int main( ) { int size; int a[10][10]; printf("Enter the size: "); scanf("%d", &size); if (size % 2 == 0) { printf("Magic square works for an odd numbered size\n"); } else { magicsq(size, a); } return 0; } void magicsq(int size, int a[][10]) { int sqr = size * size; int x = 0, y = size / 2, k; for (k = 1; k <= sqr; ++k) { a[x][y] = k; x--; y++; if (k % size == 0) { x += 2; --y; } else { if (y == size) { y -= size; } else if (x < 0) { x += size; } } } for (x = 0; x < size; x++) { for (y = 0; y < size; y++) { printf("%d ", a[x][y]); } printf("\n"); } printf("\n"); }