Magic Square In Java

import java.util.*;
class MagicSquare{
    public static void main(){
        Scanner sc=new Scanner(System.in);
        int n,x,i,j;
        System.out.println("Enter size of an array");
        n=sc.nextInt();
        int a[][]=new int[n][n];
        i=0;
        j=(n-1)/2;
        x=1;
        do{
            if(a[i][j]!=0){
                i=(i+2)%n;
                j=(j+1)%n;
            }//end of if
            a[i][j]=x++;
            i--;
            j--;
            if(i<0)
            i=n-1;
            if(j<0)
            j=n-1;
        }//do
        while(x<=n*n);
        for(i=0;i<n;i++){
            for(j=0;j<n;j++){
                System.out.print(a[i][j]+" ");
            }
            System.out.println();
        }}}//end of class

Comments

Post a Comment

Popular posts from this blog

Sort Boundary Elements Of A Matrix

Lucky Number In Java ISC

Program to fill a square matrix of size ‘n*n” in a circular fashion (clockwise) with natural numbers from 1 to n*n, taking ‘n’ as input.