answersLogoWhite

0


Best Answer

You have to create 9 empty labels on the gui, then randomize 9#'s. assign each random number to the labels in the 3x3 square. ( you have to keep in your head where each random number will be). Then create a loop that does not end until each row, (labels 1-3), each column (labels 1,4,7), and diagnal ( 1,5,9) are different unique numbers and they add to 15(or the magic number).

-----------

For magic squares with an odd number of rows/columns (i.e. 3x3, 5x5, etc.), there is a simple algorithm to fill the squares. Magic squares with even number of rows/columns do NOT follow this algorithm.

Start in the top row, middle square. Place the number 1 there. The rest of the squares are filled as follows.

Choose the next cell by moving up and to the right. If the square falls outside the squares, the next number goes in the first cell of the row above it. If there is no row above it, drop down to the bottom of the next column and place the number there. If there is no column to the right, drop immediately below and place the number there. If the cell is already filled, drop immediately below and place the number there. Continue until all cells are filled. The number in the middle of the sequence should fall in the middle column of the middle row. The formula for the total of each row/column is: total = n * ((( n * n ) / 2 ) + 0.5)

Samples:

Magic square of 3x3:

8 1 6

3 5 7

4 9 2

Each row/column adds up to: 3 * ((( 3 * 3 ) / 2 ) + 0.5) = 15

-----------------------

Magic square of 5x5:

17 24 1 8 15

23 5 7 14 16

4 6 13 20 22

10 12 19 21 3

11 18 25 2 9

Each row/column adds up to: 5 * ((( 5 * 5 ) / 2 ) + 0.5 ) = 65

This algorithm will work for ALL magic squares with an odd number of rows/columns (where number of rows is the same as the number of columns).

User Avatar

Wiki User

13y ago
This answer is:
User Avatar
More answers
User Avatar

Wiki User

14y ago

Introduction

Magic square is an ancient mathematical problem that many people try to solve. May be you see it in some magazines or your teacher might have introduced it in a class.

Details

A magic square is an arrangement of numbers from 1 to n2 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.

It is not hard to show that this sum must be n [ ( n2 + 1) / 2 ]. If we use this formula for that example output which is below, for [5x5] matrix; 5 [ ( 52 + 1 ) / 2 ] = 65.

17 24 1 8 15 65 23 5 7 14 16 65 4 6 13 20 22 65 10 12 19 21 3 65 11 18 25 2 9 65 65 65 65 65 65 65 Now, I want to show you a way to calculating magic squares in any order by using your talented computer.

Siamese method

This method is useful for calculating magic squares with odd order. It begins by placing a 1 in any location (in the center square of the top row in the above example), then incrementally placing subsequent numbers in the square one unit above and to the right. The counting is wrapped around, so that falling off the top returns on the bottom and falling off the right returns on the left. When a square is encountered which is already filled, the next number is instead placed below the previous one and the method continues as before. The method, also called de la Loubere's method. For example, if order of square is 5, we have:

void CalculateOddMagicSquare() { n=5; int matrix[5][5];

int nsqr = n * n; int i=0, j=n/2; // start position

for (int k=1; k<=nsqr; ++k) { matrix[i][j] = k;

i--; j++;

if (k%n 0) { i += 2; --j; } else { if (j==n) j -= n; else if (i<0) i += n; } } }

void DoublyEvenMagicSquare(vector<vector<int> > &matrix, int n) { vector<vector<int> > I(n, vector<int> (n, 0)); vector<vector<int> > J(n, vector<int> (n, 0));

int i, j;

//prepare I, J

int index=1; for (i=0; i<n; i++) for (j=0; j<n; j++) { I[i][j]=((i+1)%4)/2; J[j][i]=((i+1)%4)/2; matrix[i][j]=index; index++; }

for (i=0; i<n; i++) for (j=0; j<n; j++) { if (I[i][j]==J[i][j]) matrix[i][j]=n*n+1-matrix[i][j]; } }

void SinglyEvenMagicSquare(vector<vector<int> > &matrix, int n) { int p=n/2;

vector<vector<int> > M(p, vector<int> (p, 0)); MagicSquare(M, p);

int i, j, k;

for (i=0; i<p; i++) for (j=0; j<p; j++) { matrix[i][j]=M[i][j]; matrix[i+p][j]=M[i][j]+3*p*p; matrix[i][j+p]=M[i][j]+2*p*p; matrix[i+p][j+p]=M[i][j]+p*p; }

if (n==2) return;

vector<int> I(p, 0); vector<int> J;

for (i=0; i<p; i++) I[i]=i+1;

k=(n-2)/4;

for (i=1; i<=k; i++) J.push_back(i);

for (i=n-k+2; i<=n; i++) J.push_back(i);

int temp; for (i=1; i<=p; i++) for (j=1; j<=J.size(); j++) { temp=matrix[i-1][J[j-1]-1]; matrix[i-1][J[j-1]-1]=matrix[i+p-1][J[j-1]-1]; matrix[i+p-1][J[j-1]-1]=temp; }

//j=1, i

//i=k+1, k+1+p

i=k; j=0; temp=matrix[i][j]; matrix[i][j]=matrix[i+p][j]; matrix[i+p][j]=temp;

j=i; temp=matrix[i+p][j]; matrix[i+p][j]=matrix[i][j]; matrix[i][j]=temp; }

void PrintMagicSquare(vector<vector<int> > &matrix, int n) { for (int i=0; i<n; i++) { for (int j=0; j<n; j++) printf(" %3d", matrix[i][j]);

printf("\n"); }

printf("\n\n"); } Conclusion

Enjoy!

>>>>>>> This Is A Very Easy Coding For Begineers <<<<<<<

Although the above mentioned trick is the same

#include<stdio.h>

#include<conio.h>

void main()

{

int i,j=1,k,n,a[22][22],p,q,r,count=0;

clrscr();

A:

printf("Enter No. Of Rows Or Columns(Should Be Odd) : ");

scanf("%d",&n);

printf("\n");

if(n%2==0)

{

printf("Enter Odd No.s Only\n\n");

goto A;

}

k=(n+1)/2;

for(p=1;p<=n;p++)

{ for(q=1;q<=n;q++)

{

a[p][q]=NULL;

}

}

for(i=1;i<=(n*n);i++)

{

if(a[j][k]==NULL)

{

a[j][k]=i;

}

else

{

j=j+2;

k--;

if(j==n+2)

j=2;

if(k==0)

k=n;

if(j==0)

j=n;

if(k==n+1)

k=1;

a[j][k]=i;

}

j--;

k++;

if(j==0)

j=n;

if(k==n+1)

k=1;

}

for(p=1;p<=n;p++)

{

for(q=1;q<=n;q++)

{

r=a[p][q];

while(r>0)

{

r=r/10;

count++;

}

if(count==1)

printf(" 0%d",a[p][q]);

else

printf(" %d",a[p][q]);

if(q%n==0)

printf("\n\n");

count=0;

}

}

for(p=1;p<=n;p++)

{

for(q=1;q<=n;q++)

{

}

}

getch();

}

>>>Abhi<<<

This answer is:
User Avatar

User Avatar

Wiki User

12y ago

#include<stdio.h>

#include<string.h>

void main()

{

int kute=0;

int ms[100][100],n,i,j,num;

while(scanf("%d",&n)==1)

{

if(!n%2)

{

printf("Enter a odd number 1-99\n");

continue;

}

memset(ms,0,sizeof(ms));//set all element to 0 as well false

num=1;i=n/2;j=n-1;//1st step

while(1)

{

if(num>n*n)break;

if(i==-1&&j==n){j=n-2;i=0;}//3rd condition

else {

if(j==n)j=0;//1st condition helper if next number is goes to out of box right side

if(i<0)i=n-1;//1st condition helper if next number is goes to out of box upper side

}

if(ms[i][j]){j--;j--;i++;continue;}//2nd condition

else

ms[i][j]=num++;//set number

j++,i--;//1st condition

}

//print magic square

printf("The Magic Square for %d:\nSum of each row or column %d:\n\n",n,(n*n*n+n)/2);

for(i=0;i<n;i++)

{

for(j=0,num=0;j<n;j++)

{

printf("%2d ",ms[i][j]);

num+=ms[i][j];

}

printf(" %d\n\n",num);

}

getch();

}

This answer is:
User Avatar

User Avatar

Wiki User

12y ago

/*Program to takes the the data of a 3x3 matrix and check if the given matrix is magic

square or not*/

#include <stdio.h>

#include <conio.h>

int num[3][3];

int sum[8];

int r,c,i;

/*Function to take the value in matrix from user*/

void read_matrix()

{

for(r=0;r<3; r++)

{

for(c=0;c<3; c++)

{

printf("Enter value for %d %d::",r,c);

scanf("%d",&num[r][c]);

}

}

}

/*Function to print matrix and get the sum of rows,cols and diaglons*/

void print_calc_rows_cols()

{

int sum_row,sum_col,ctr=0;

/*Print the Matrix and get the sum of rows*/

for(r=0;r<3; r++)

{

sum_row=0;

for(c=0;c<3; c++)

{

printf("\t%d",num[r][c]);

sum_row=sum_row+num[r][c];

}

sum[ctr]=sum_row;

ctr++;

printf(":: %d",sum_row);

printf("\n");

}

printf("\t::\t::\t::\n");

/*Get the sum of columns*/

for(c=0;c<3;c++)

{

sum_col=0;

for(r=0;r<3;r++)

sum_col=sum_col+num[r][c];

sum[ctr]=sum_col;

ctr++;

printf("\t%d",sum_col);

}

printf("\n");

/*Get the sum of diagnols*/

sum[6]=num[0][0]+num[1][1]+num[2][2];

sum[7]=num[0][2]+num[1][1]+num[2][0];

}

/*Function to Check the sum of rows,cols and diagnols*/

char check_matrix()

{

char c;

for(i=0;i<3; i++)

{

if(sum[i]==sum[i+1])

c='y';

else

{

c='n';

break;

}

}

return c;

}

void main()

{

char c;

clrscr();

read_matrix();

print_calc_rows_cols();

c=check_matrix();

/*Print the result*/

if(c=='y')

printf("\nThis Matrix is a Magic Square");

else

printf("\nThis Matrix is Not a Magic Square");

getch();

}

This answer is:
User Avatar

User Avatar

Wiki User

11y ago

hi i am abhinav from India

its my first post...

i am going to show

you a code to make a 3x3 magic square if you want to make 5x5 or more simply change 3 wherever occured in program by 5 or some other odd no as your need

#include<stdio.h>

#include<conio.h>

main()

{

int a[3][3];

int i,j,p,q,k;

int n=3;

for(p=0;p<n;p++)

{

for(q=0;q<n;q++)

{

a[p][q]=0;

}

}

i=0;

j=(n-1)/2;

a[i][j]=1;

printf("aij is%d\n",a[i][j]);

for(k=2;k<=n*n;k++)

{

i--;

j++;

if(i==-1)

{

i=n-1;

}

if(i==n)

{

i=0;

}

if(j==-1)

{j=n-1;

}

if(j==n)

{

j=0;

}

if(a[i][j]!=0)

{

i=i+2;

j=j-1;

if(i>n-1)

{

i=i-n;

}

if(j==-1)

{

j=n-1;

}}

a[i][j]=k;

printf("a%d%d is %d\n",i,j,k);

}

for(p=0;p<3;p++)

{

for(q=0;q<3;q++)

{

printf("%d\t",a[p][q]);

}

printf("\n");

} }

This answer is:
User Avatar

User Avatar

Wiki User

7y ago

Let me know if this code works

#include <iostream>

#include <iomanip>

using namespace std;

int size(bool flag)

{

int test; if(flag)

{

do

{

test=(int)(double(rand())/double(RAND_MAX)*14.0+3.0);

}

while(test%2==0);

return test;

}

else return 7;

}

int main()

{

int n = 7;

int row, col, size;

int magic[19][19];

for(int j=0 ; j<n ; j++)

{

for(int k=0 ; k<n ; k++)

{

magic[j][k] = 0;

}

}

row=1; col=(n+1)/2;

magic[row-1][col-1]=1;

for(int i=2 ; i<=(n*n) ; i++)

{

row-=1;

col-=1;

if(row==0 && col==0)

{

col++; row+=2;

}

else if(row==0) row=n;

else if(col==0) col=n;

else if(magic[row-1][col-1]!=0)

{ col++; row+=2;

}

magic[row-1][col-1]=i;

}

for (row=1; row<=n; row++)

for(col=1; col<=n; col++)

magic[row][n+1]+=magic[row][col];

for(col=1; col<=n; col++)

for(row=1; row<=n; row++)

magic[n+1][col] += magic[row][col];

for(int r=0; r<(n+1) ; r++)

{

cout<<endl;

for(int c=0; c<(n+1) ; c++)

{

cout << setw (5) << magic[r][c];

} cout<<endl;

}

return 0;

}

This answer is:
User Avatar

User Avatar

Wiki User

12y ago

Hiya!!

Alright, a c program for magic squares....here you go...

It seems there has been no answer to the question on how to detect a magic square on this site. This being a common question in programming, now, I shall assume more and that because such questions on programs on magic squares have been asked before, I guess you could do with more stuff...I'm putting down the methods for the other kind of program in this category- The one on detecting a magic square. This too is for 3x3.

given below is the method for constructing the program. Follow it closely, then we shall proceed with the program.

1. Creating matrix- Use arrays which can keep your numerical elements as a matrix of odd order 3. (easy!)

2. Addition of elements- Devise a way to add elements of the matrix in rows, columns, and diagonals. (easy!)

3. Check sum- Write some lines so the compiler can compare the sums in the above step.(easy!)

4. Detection- The sums compared should be equal to detect the matrix as a magic square, and unequal to detect is as not one.(easy!)

5. Horray!!!

This might look lazy on my part, but its all there is. Frankly, the program is a piece of cake, but I guess it would be a bit triffling on the code construction. Since the question asks about 'going about making the program', I think I wont post the code itself(which you can find anywhere anyway), but I'll write down the detailed explicit constructs for the C code for detection of 3x3 magic squares. Trying to keep it nice and short:)

1. You use here the files stdio.h and conio.h as header files(to keep it easy, nice, and short)

2. Since this program basically makes use of arrays (again to keep it easy), you could go with single-element ones or the matrix(2D) ones. I prefer the latter, and shall use the same.

3. We begin with declaration of the variables and arrays we shall use throughout the code. Its better to put them just below the headers and outside any function scope.Say for example you declare array matrix[3][3] (the main 2D matrix for storing input elements), an array say sum[8] (for storing sum of elements of rows, columns, and the diagonals IN ORDER), and some variables say a, b, c (to use in the rest of the code) . all these shall be as the int variables.

4. Now we reach forks- you can either use just one 'main' function and make your hands dirty, or divide the code operations into different 'functions' to make your work easier. Again, I shall go by the latter method. We make use of four functions- one for reading the input(say void read()),one for calculation of the desired sums(say void calc()),one for checking the sums (say char check()), and the last one ofcourse for the program execution (the main() function).

5. Lets go step by step. We begin with the reading function. (Assuming you know the syntax usage). Since we have used a 2D array of 9 elements, we ask the user to input 9 elements. This can be done in proper manner by displaying a preformed sentence asking the person to input, for example, the element in 'row 1 and column 1'. This can be done easily using 'for' loops and initially declared variables to restrict entry to only 9 elements. Then, our program should read the input elements and store them in memory slots. The code would look something like:

void read()

printf("Enter element for row %d and column %d",r,c);

scanf("%d",&amp;mat[r][c]);

This is an easy step and universal for 2D array input. (You can use the conio.h function clrscr() here if you wish.)<

2. Now that we've read the elements, we must calculate the sums we need. For this function (void calc()), you need to use new integer variables (say rowsum, column sum)for storing sums in rows, columns, and diagonals. This is a very simple step, and all you must do is make separate 'for' loops for row sum, column sum. The diagonal sum would come as a single element and we can directly add elements of the matrix for the same. for the row sums, you can create a 'for' loop restricting input to three elements of a row and initialize rowsum to zero inside. Then all you do is select each row independently and add the elements in it and store the addition to the sum[] location (this should not be a problem...). You do this for all three rows.

Proceed similarly for sumcolumn to add elements in columns.

Now we add elements of the diagonals. This is trifle,and need only add locations of diagonal elements from our original matrix. I'm writing the line directly here.

sum[6]=matrix[0][0]+matrix[1][1]+matrix[2][2];

sum[7]=matrix[0][2]+matrix[1][1]+matrix[2][0];

the sum[6] and sum[7] array locations here indicate the locations for diagonal sums.

This function of calculating sums ends here. We now proceed to somparing the sums.

. This step includes designing the function to check sums computed in the earlier function. This could be a bit tricky for most:(, so I'll explain it here.

The type of our function here would be 'char' because we want it to 'return' a value to the executable function. This function would return a value for a matrix being a magic square, and a value for the matrix not being a magic square. This step shall go easy on us because we added the desired sums into a single basic array of 8 elements. All we need to do is compare each sum element in this array and check if it equals its fellows(you know what I mean:)). For this, we declare a character, say 'z', inside the function and create a 'for' loop below it with variable 'c'(declared at the start) to restrict detection to the 9 element matrix. now we simply put a condition in the loop- 'If' element in sum[i] is equal to element in sum[i+1], we return a value (anything!) to the executable funtion, 'else' we return some other value (anything!) to the executable funtion. This piece of code for the check (cake...) would look something like:

for(i=0;i&lt;3; i++)

{if(sum[i]==sum[i+1])c='l';

else

{c='p':break;}

return c;

As an aliter, you can also check if the sum[i] equals 15(coz thats the declared sum for a 3x3 magic square). however, the method I mentioned works as well(and looks professional;))

4. Bravo! The main functions for processing of input have now ended, and we need the output now. For this we have the 'main()' function. Since this has no return thye, you can use void main().OK, so all we do here now is call the functions used above and display on the screen if the input makes a magic square or not.

So we declare a character, say 'e', to collect the return value given by the 'check' function, and call the other two functions 'read' and 'calc' into the main function. This is not hard on syntax, and to the rescue;).Finally all you do is display the output usinf the printffunction. You use the value returned by 'check()' to determine what conclusion you must print.

5. HOORAY!!!

THE CODE FOR CHECKING MAGIC SQUARES IS NOW READY!!!

Just input values now and clap to the awesome results...:p

As extra effort, you could beautify your display by aligning all display sentences in a proper way, or showing the input matrix alongwith the final result, and showing the sum alongside the matrix....if you know what I mean...:) create the code now and see it work.

This answer is:
User Avatar

User Avatar

Wiki User

11y ago

#include <stdio.h>

// max values of rows and columns in the array

#define MAX_ROWS 99

#define MAX_COLUMNS 99

int main(void)

{

int magic_square[MAX_ROWS][MAX_COLUMNS], next_row, next_column, last_row, last_column;

int size, num, sum;

printf("This program creates a magic square of a specified size.\n");

printf("The size must be an odd number between 1 and 99.\n");

printf("Enter size of magic square: ");

scanf("%d", &size);

// Loop to initialize each element of the array 'magic_square' with 0

for (next_row = 0; next_row < size; next_row++)

for (next_column = 0; next_column < size; next_column++)

magic_square[next_row][next_column] = 0;

// placing the number 1 in the middle of row 0

next_row = last_row = 0;

next_column = last_column = (size / 2);

magic_square[next_row][next_column] = 1;

for (num = 2; num <= (size * size); num++)

{

next_row = (last_row + (size - 1)) % size; // sets the next row in which next element is to be placed

next_column = (last_column + 1) % size; // sets the next column in which next element is to be placed

if (magic_square[next_row][next_column] == 0) // condition to check whether a particular array element is preoccupied or not

{

magic_square[next_row][next_column] = num;

last_row = next_row;

last_column = next_column;

}

else

{

next_row = (last_row + 1) % size; // sets the next row in case of the next element in the array is preoccupied

next_column = last_column; // sets the next column in case of the next element in the array is preoccupied

magic_square[next_row][next_column] = num;

last_row = next_row;

last_column = next_column;

}

}

// loop to print the array 'magic_square'

for (next_row = 0; next_row < size; next_row++)

{

for (next_column = 0; next_column < size; next_column++)

printf("%4d", magic_square[next_row][next_column]);

putchar ('\n');

}

/* CHECK

*

printf("\n\n\n");

sum = 0;

for (next_row = 0; next_row < size; next_row++)

{

for (next_column = 0; next_column < size; next_column++)

sum = sum + magic_square[next_row][next_column];

printf("sum of row %d = %d\n", next_row, sum);

sum = 0;

}

printf("\n\n\n");

for (next_row = 0; next_row < size; next_row++)

{

for (next_column = 0; next_column < size; next_column++)

sum = sum + magic_square[next_column][next_row];

printf("sum of column %d = %d\n", next_row, sum);

sum = 0;

}

printf("\n\n\n");

for (next_row = 0, next_column = 0; next_row < size; next_row++, next_column++)

sum = sum + magic_square[next_row][next_column];

printf("sum of diagonal 1 = %d\n", sum);

sum = 0;

printf("\n\n\n");

for (next_row = 0, next_column = (size - 1); next_row < size; next_row++, next_column--)

sum = sum + magic_square[next_row][next_column];

printf("sum of diagonal 2 = %d\n", sum);

sum = 0;

*

*/

return 0;

}

This answer is:
User Avatar

User Avatar

Wiki User

11y ago

how to write a c program for magic square puzzle

This answer is:
User Avatar

Add your answer:

Earn +20 pts
Q: Want program for magic square using c?
Write your answer...
Submit
Still have questions?
magnify glass
imp
Related questions

How do you fly using magic spells?

You can't fly with magic spells as there is no such thing as magic. If you want to fly, then you best option is to learn hang gliding or get a pilot's license.


In LittleBigPlanet PSP how do you place a Magic Mouth on a story character in a created level?

just like anything else! just press x when the magic mouth is where you want it. then press square to tweak it and you got it from there.


How do you make shortcuts for magic in kingdom hearts 2?

When you press start, there's is a menu, and there is a place where you can customize items and magic. There you can choose 4 types of magic that you want as "ex", "square", "triangle" and "circle". After you do that, while outside of the menu, you press L1 and any one of these buttons and it will do the magic you chose it to be.


You want C program on students information record using file handling?

yes sir


How can a 1GB program run in only 512MB of memory?

Through the magic of Virtual Memory, though it might page to disk more often than you want.


How do you write a program using 57252077?

Please be more explicit, 57252077 is a bit of a mystery. Do you want a program that uses the number 57252077 in some way?


Who can teach me magic?

It depends on what type of magic you want to learn.


How do you use Lunar Magic?

i want to use lunar magic but i have no idea how!!!!!!


How do you say 'all i want is my magic' in German?

all i want is my magic = Alles was ich will ist meine Magie


Is it good to learn magic?

It is not bad to learn Magic. But ask yourself why you want to learn Magic. It is not easy...


What i do if this message appear ''another program is currently using this file ''?

Maybe there is still one software is using this file! You should close the software first if you want to operate the file!,for examble,if your computer has a movie file in D disk,and the media software is using it meanwhile,at this time ,you want to delete the movie file for some reasons,when you click"delete",the system will alert you that "another program is currently using this file"! So what you need to do is to close the software which is using the file you want to delete!


How do you be magic?

If you want to be magic you have to sit down for a very long time and hum