Here's a C program to generate magic square with output. This program uses C concepts like GOTO statement, Modulus in C, Multidimensional Arrays, IF-Else Condition, For loop and Nested Loops.
What is Magic Square? A magic square of order n is an arrangement of n2 numbers, usually distinct integers, in a square, such that the n numbers in all rows, all columns, and both diagonals sum to the same constant.
![]() |
| Magic Square |
# include <stdio.h> # include <conio.h>
void main()
{
int n, i, j, c, a[9][9] ;
clrscr() ;
printf("Enter the size of the magic square : ") ;
scanf("%d", &n) ;
if (n % 2 == 0)
{
printf("\nMagic square is not possible") ;
goto end ;
}
printf("\nThe magic square for %d x %d is :\n\n", n, n) ;
j = (n + 1) / 2 ;
i = 1 ;
for(c = 1 ; c <= n * n ; c++)
{
a[i][j] = c ;
if(c % n == 0)
{
i = (i + 1);
goto loop ;
}
if(i == 1)
i = n ;
else
i = i - 1 ;
if(j == n)
j = 1;
else
j = j + 1 ;
loop : ;
}
for (i = 1 ; i <= n ; i++)
{
for (j = 1 ; j <= n ; j++)
{
printf("%d\t", a[i][j]) ;
}
printf("\n\n") ;
}
end : ;
getch() ;
}
Output of above program
Enter the size of the magic square : 3
The magic square for 3 x 3 is :
8 1 6
3 5 7
4 9 2

plz tell me logic to make magic square.
ReplyDeleteThis program is the logic to generate magic square!! What else do you wanna know?
ReplyDeleteHow to tracing the program pls say
Deletemagic square with even size is also possible......
ReplyDeleteformula for magic constant i.e. sum of elements in rows, columns and diagonals
is
m=n(n*n+1)/2
where n is the size of matrix
go to wikipedia for more info
plz dont use goto's!! its a hated thing among c programmers.
ReplyDeleteSir what is the procedure to trace this program
ReplyDeletebrother i do not claer from this,please kindly clear me
ReplyDeleteif(c % n == 0)
{
i = (i + 1);
goto loop ;
}
if(i == 1)
i = n ;
else
i = i - 1 ;
if(j == n)
j = 1;
else
j = j + 1 ;
loop : ;
}
for (i = 1 ; i <= n ; i++)
{
for (j = 1 ; j <= n ; j++)
{
printf("%d\t", a[i][j]) ;
}
printf("\n\n") ;
}
end : ;
getch() ;
}
Hi There,
ReplyDeleteYour writing shines! There is no room for gibberish here clearly you have explained about C Program to Generate Magic Square is a right choice to advance my career Keep writing!
Write a LEX program (I know this is in C) that identifies words from the previous set of phrases, such that an input of the form "triangle BCD" returns:
---Triangle: a geometric entity (loll at that)
---BCD: name of a geometric entity
b) Define the tokens, lexemes and patterns to be found in formal expressions concerning these three sentences.
c) Construct the finite automaton that corresponds to the formal expressions to describe the names of geometric entities in that language. Use this to see if the name AYZ is recognizable.
But nice Article Mate! Great Information! Keep up the good work!
Cheers,
Franda