Thursday, February 24, 2011

BlueJ program on Magic Box

Magic box is a square matrix where sum of the values of each rows, columns and disgonals are same.

Codes of the magic box program


import java.io.*;
class Magic
{
int arr[][],arr1[];
int n,i,j,x=0,r,c;
int flag;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public void take()throws Exception
{
System.out.println("\nEnter the size of array(row and column same):");
n=Integer.parseInt(br.readLine().trim());
arr=new int[n][n];
arr1=new int[2*n+2];
for(i=0;i< n;i++)
{
for(j=0;j< n;j++)
{
System.out.println("\nEnter the value:");
arr[i][j]=Integer.parseInt(br.readLine());
}
}
System.out.println("\nThe matrix is\n");
for(i=0;i< n;i++)
{
r=0;
c=0;
for(j=0;j< n;j++)
{
System.out.print(arr[i][j]+" ");
if(i==j)
arr1[2*n]=arr1[2*n]+arr[i][j];
if(i+j==n-1)
arr1[2*n+1]=arr1[2*n+1]+arr[i][j];

r=r+arr[i][j];
c=c+arr[j][i];
}
System.out.println();
arr1[x]=r;
arr1[x+n-3]=c;
x++;
}

for(i=0;i< x-1;i++)
{
if(arr1[i]!=arr1[i+1])
break;
}
if(i==x-1)
System.out.println("YES IT IS A MAGIC BOX.");
else
System.out.println("IT IS NOT A MAGIC BOX.");

}
public static void main(String args[])throws Exception
{
Magic ob=new Magic();
ob.take();
}
}

3 comments:

Subscribe via email

Enter your email address:

Delivered by FeedBurner