A square matrix is the matrix in which number of rows equals the number of columns. Thus, a matrix of order n*n is called a Square Matrix. Write a program in Java to create a double dimensional array of size nxn matrix form and fill the numbers in a circular fashion (anticlock-wise) with natural numbers from 1 to n2, taking n as an input. The filling of the elements should start from outer to the central cell.
import java.util.*;
public class CircleMat {
int n;
int[][] A;
void input() {
Scanner sc = new Scanner(System.in);
System.out.print("Value of n: ");
n = sc.nextInt();
sc.close();
}
void fillMat() {
A = new int[n][n];
int a = 0, x = 1;
while (x <= n * n) {
int b = n - 1 - a;
for (int i = a; i <= b; i++)
A[i][a] = x++;
for (int i = a + 1; i <= b; i++)
A[b][i] = x++;
for (int i = b - 1; i >= a; i--)
A[i][b] = x++;
for (int i = b - 1; i >= a + 1; i--)
A[a][i] = x++;
a++;
}
}
void display() {
System.out.println("Circular Matrix :- Anti Clockwise");
for (int x = 0; x < n; x++) {
for (int y = 0; y < n; y++)
System.out.print(A[x][y] + "\t");
System.out.println();
}
}
public static void main(String[] args) {
CircleMat a = new CircleMat();
a.input();
a.fillMat();
a.display();
}
}
Name | Type | Uses |
---|---|---|
global | ||
n | int | to store the dimensions of the square matrix |
A | int[][] | the matrix in which the pattern to be printed will be stored |
void main() | ||
a | CircleMat | object to call it's method |
void display() | ||
x, y | int | counter variables to iterate over the matrix |
void input() | ||
sc | Scanner | object to take user input |
void fillMat() | ||
x | int | this is the value which will be stored in the matrix |
a, b | int | indices to help us give printing location |