Magic Square in JAVA


/**
 * Magic Square
 * version.... 1.0.0
 * Copyright: ECP-II
 * author@ Ishwar ECP-II
 * Asst: ECP-II
 * Date: 10:06 AM -- 30/11/2017
 * 
 *  Description:
 *  This program is a first level of Artificial Intelligence;
 *  When you give an odd input you will be provided with a square [n x n] in which all the rows, columns and diagonals, 
 *  when summed up, gives the same result; 
 *  Enjoy the Program ;)
 */
import java.util.Scanner;
//Defining class MagicSquare
public class MagicSquare {
int n;
//Method to get input from the User
void input(){
//Creating object for class Scanner
@SuppressWarnings("resource")
Scanner sc=new Scanner(System.in);
System.out.println("*******************************************************************");
System.out.println("*****************************MAGIC SQUARE**************************");
System.out.println("*******************************************************************\n\n");
System.out.println("Enter an ODD number: ");
//Storing the input given by user in the instance variable 'n' using scanner object
n=sc.nextInt();
}
           
//Method to create The Magic Square
void magic(){
    System.out.println("\f ");
System.out.println("Here U GO: -\n");
System.out.println("*******************************************************************\n");
        //Declaring method variables 'r' for rows, 'c' for columns and 's' for sums
int r,c,s=0;
//Initializing 2D array 'a' with size n x n 
int a[][] = new int[n][n];
//Initializing rows and columns to the top middle element 
r=0;
c=n/2;
for(int i=1;i<=n*n;i++){
//Storing the elements in the matrix one by one
a[r][c]=i;
r=r-1;//up
if(r<0)
r=r+n;//returning to the last row
c=c+1;//right
if(c>=n)
c=c-n;//returning to the first column
    //Condition to check if there is already an element in the cell
if(a[r][c]!=0){
//Placing the element down the previous element 
r=r+2;
    c=c-1;
    if(r>=n)
r=r-n;//returning to the first row
    if(c<0)
c=c+n;//returning to the last column
}
}
//Printing the array in a structured Layout
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
System.out.print(a[i][j]+"\t");
}
System.out.println("\n\n");
}
System.out.println("\n*******************************************************************");
//Calculating the Sum of Rows/Columns/Diagonals
for(int i=0;i<n;i++)
s=s+a[0][i];
        System.out.println("\n\n*******************************************************************");
System.out.println("Sum of the Rows/Columns/Diagonals : "+s);
        System.out.println("*******************************************************************");
}
public static void main(String args[]){
//Creating object for the class MagicSquare
MagicSquare m=new MagicSquare();
m.input();//Calling input Method
m.magic();//Calling magic Method


}

}


Comments

Popular posts from this blog

java PROJECT for icse students : CINEMASTER

Easy Sorting in Java