u

Thursday, 7 June 2012

C++ program to creates a magic square box of order n x n. The speciality of a magic square box is that the sum of elements of any row or any column is always equal

C++ program to creates a magic square box of order n x n. The speciality of a magic square box is that the sum of elements of any row or any column is always equal


#include <stdio.h>
#include <conio.h>
#include <math.h>
#include <stdlib.h>
#include <alloc.h>
int arr[10][10], n, a,b,i;
void magic(int , int , int, int);

void main()
{
int j,x,k;
clrscr();
printf("\n Enter size of matrix (n X n, where n is odd):");
scanf("%d", &n);
printf("\n Enter 1st element of the %d sequential elements:",n*n);
scanf("%d", &x);
for (i=0; i<n; i++)
{
for (k=0; k<n; k++)
{
arr[i][k]=-1;
}
}
arr[0][n/2]=x;

magic(0,n/2, x, n);
printf("\n");
for (i=0; i<n; i++)
{
for (k=0; k<n; k++)
{
printf(" %3d ", arr[i][k]);
}
printf("\n");
}
getch();
}


void magic( int a, int b, int x, int n)
{
int c;
c=1;
for (x=x+1,i=2; i<=n*n; i++,c++,x++)
{
if(c<n)
{
a=a-1;
b=b-1;
if (a==-1)
a=n-1;
if (b==-1)
b=n-1;
}
else
{
a=a+1;
c=0;
}
arr[a][b]=x;
}

}

0 comments:

Post a Comment

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More