Magic Matrix in Java
Magic matrix is such an odd sized matrix whose sum of each row, column and diagonal are equal. The following video is an implementation of an odd sized magic matrix.
Source code for magic matrix
import java.util.*;
class MagicSquare{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int n,i,j,r,c;
System.out.println("Enter the size of the matrix:");
n=sc.nextInt();
if(n%2==0)
System.out.println("Only odd size matrix:");
else
{
r=0;c=n/2;
int a[][]=new int[n][n];
for(i=1;i<=n*n;i++)
{
a[r][c]=i;
if (i%n==0)
r++;
else
{
r--;
c--;
if(r<0 n="" p="" r="">0>
if(c<0 c="" n="" p="">0>
}
}
System.out.println("The magic square:");
for(i=0;i
{
for(j=0;j
{
System.out.printf("%3d",a[i][j]);//printf() for formatted output
}
System.out.println();
}
}
}
}