C-PROM 2013 (PROBLEM 3 : THE SQUARE MATRIC)

PROBLEM 3 : THE SQUARE MATRIC


In mathematics, a square matrix is a matrix with a same number of rows and columns. An n-by-n matrix is known as a square matrix of order n. For instance, this is square matrix of order 3:


Write a program that is able to display a square matrix of any order as specified by the user. All the entries of the matrix are 1s except the entries in the main diagonal and anti-diagonal. The entries in both diagonals should be 0s.

Input
Any integer number.

Output
The square matrix of any order as specified by the user with its entries in principal diagonal and anti-diagonal is 0s. The rest of the entries remain to be 1s.

Sample Input
Sample Output
7







4
0 1 1 1 1 1 0
1 0 1 1 1 0 1
1 1 0 1 0 1 1
1 1 1 0 1 1 1
1 1 0 1 0 1 1
1 0 1 1 1 0 1
0 1 1 1 1 1 0

0 1 1 0
1 0 0 1
1 0 0 1
0 1 1 0


Solution : 
import java.util.*;
public class diagonal {
public static void main(String [] args) {
Scanner scan = new Scanner(System.in);
int num=0;
while(scan.hasNextInt()) {
num = scan.nextInt();
int no = num-1;
for(int y=0;y<num;y++) {
for(int z=0;z<num;z++) {
if( z==y || z==(no-y))
System.out.print("0");
else
System.out.print("1");
}
System.out.print("\n");
}
   System.out.println("");
}
}
}

Share this

Related Posts

Previous
Next Post »