We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you a podcast all about Citrix Workspace, moving to the cloud, and analytics & intelligence. Episode 2 coming soon!Listen Now

x

# WRITE A PROGRAM FOR MAGIC SQUARES

on
Medium Priority
586 Views
WRITE A PROGRAM THAT GENERATES A MAGIC SQUARE BY THE FOLLOWING METHOD.  AN 5X5, AN 7X7, AND A 3X3 SQUARE.  THE SUM OF EVERY ROW, THE SUM OF EVERY COLUMN AND THE SUM OF THE TWO DIAGONALS MUST BE EQUAL FOR A SQUARE TO BE MAGIC.

Comment
Watch Question

## View Solution Only

CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2015

Commented:
Commented:
This sounds like a high-complexity problem, but there is a very simple solution for the particular case of odd-length magic squares. The following program illustrates this solution. It is written for Borland C++ using only ANSI C commands, so you should have no problems porting it.

------- BEGIN PROGRAM CODE
#include <stdio.h>
#include <mem.h>

#define MAXN 9
typedef int Square[MAXN][MAXN];

int main() {
Square s={{0}};
int i,x,y,xnew,ynew,n;

/* get length of square */
do {
printf("Type length of square (odd number between 3 and %d): ",MAXN);
scanf("%d",&n);
} while(n%2==0 || n<3 || n>MAXN);

/* calculate magic square */
x=0;
y=n/2;
for(i=0; i<n*n; i++) {
/* place current value */
s[x][y]=i+1;
/* find next spot */
xnew = (x+n-1)%n;
ynew = (y+n-1)%n;
if(s[xnew][ynew]==0) {
x=xnew;
y=ynew;
} else
x=(x+1)%n; /* y remains the same */
}

/* display result */
for(y=0; y<n; y++) {
for(x=0; x<n; x++)
printf("%d\t",s[x][y]);
printf("\n");
}

return 0;
}
------- END PROGRAM CODE

That's it. The complexity is proportional to n - you can't do it any faster than that. You can, of course, create larger squares by increasing the value of MAXN.

Not the solution you were looking for? Getting a personalized solution is easy.

Commented:
Sorry, my mistake. The complexity is proportional to n squared. But I still think you won't be able to make it any faster.

Commented:
THANK YOU!  I BEING A WEEKEND WARRIOR ON LEARNING HOW TO PROGRAMM IN 'C' FOUND THE SOLUTION TO BE VERY USEFUL.  SOME BOOKS I'VE PURCHASED IS ARE EITHER USEFUL OR TOO "TECH."  I'M USING MICROSOFT VISUAL C/C++ 5.0, THE ONLY THING I HAD TO DO TO GET RID OF AN COMPILE ERROR WAS TO REMOVE #INCLUDE <MEM.H> AND IT DID ITS THING.
Access more of Experts Exchange with a free account
##### Thanks for using Experts Exchange.

Limited access with a free account allows you to:

• View three pieces of content (articles, solutions, posts, and videos)
• Ask the experts questions (counted toward content limit)
• Customize your dashboard and profile