Saturday, November 21, 2009

Arranging numbers inside a Square Matrix in a particular order

Hello my friends ,
The program given below receives a matrix order and prints the matrix in a particular fashion.
For eg : if the program receives 4 as input then it produces a matrix like this given below:

1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7

ie , it produces n square elements arranged in a particular fashion

Program
import java.io.Console ;
public class SquareRoot{
public static void main(String[] args){
Console console = System.console() ;
System.out.print("Enter the order of matrix = ");
String order = console.readLine() ;
int n = Integer.parseInt(order) ;
int arr[][] = new int[n][n] ;
int y , x ,count ;
int x_max , y_max , y_min ,x_min ;
x_max = y_max = n-1 ;
x_min = y_min = 0 ;
int i = 1 ;
int value = n ;
value -= 1 ;
int square = n*n + 1 ;
for(;i!=square;){
x = x_min ;
y = y_min ;
while((y <= y_max)&& i!=square){ arr[x][y] = i ; y++; i++ ; } y -= 1 ; x++ ; while((x <= x_max)&& i!=square){ arr[x][y] = i ; x++; i++ ; } x -= 1 ; y-- ; while((y >= y_min)&& i!=square){
arr[x][y] = i ;
y--; i++ ;
}
y += 1 ; x -= 1;
while((x > x_min)&& i!=square){
arr[x][y] = i ;
x--; i++ ;
}
x += 1 ; y += 1 ;
value -= 1 ;
x_max = y_max = value ;
x_min = x ;
y_min = y ;
}
System.out.println("\nMatrix is :");
for(int l=0;l


OUTPUT


Enter the order of matrix = 7

Matrix is :
1 2 3 4 5 6 7
24 25 26 27 28 29 8
23 40 41 42 43 30 9
22 39 48 49 44 31 10
21 38 47 46 45 32 11
20 37 36 35 34 33 12
19 18 17 16 15 14 13

No comments:

Post a Comment