Friday, June 21, 2019

Magic Matrix in Java

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="">
                    if(c<0 c="" n="" p="">
                }
            }
            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();
            }
        }
    }
}

        

No comments:

Post a Comment

  Source Code for :   Displaying all possible fangs of a Vampire Number in Java import java.util.*; class Number {     public static void ma...