Advertisements
Home > Java > Java Program to print MAGIC Square – Q15

Java Program to print MAGIC Square – Q15


Q15: Java Program to print MAGIC Square

class magicSq{
	public static void main(String args[]){
		int l, i, j, x, y, val=1;
		
		l = Integer.parseInt(args[0]);
		int mat[][] = new int[l][l];
		
		x = 0;
		y = l/2;
		
		mat[x][y] = val++;
		while(val <= l*l){
			
			x--;
			y--;
			if((x < 0) && (y < 0)){
				x = 1;
				y = 0;
			}
			if(x < 0)
				x = l-1;
			if(y < 0)
				y = l-1;
			
			if(mat[x][y] != 0){
				x+=2;
				y++;
			}
			mat[x][y] = val++;
			System.out.println(x + " " + y + " " + mat[x][y]);
		}
		
		for(i=0; i<l; i++){
			for(j=0; j<l; j++){
				System.out.print("  " + mat[i][j]);
			}
			System.out.println();
		}
	}
}

… from College notes (BCA/MCA assignments):


Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: