Matrix Pattern in Java language using For loop
ADVERTISEMENTS
Matrix pattern in java language using for loop. In this article, you will learn how to print the matrix pattern in java language using for loop.
Source Code
// Matrix Pattern in Java language using For loop
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x, i, j, k, d = 1, m;
// x - denotes the number of rows
System.out.println("-----Enter the total number of rows-----");
x = in.nextInt();
int mat[][];
mat = new int[x][x];
for ( i = 0; i < x; i++) {
j = i;
k = 0;
for ( j = i; j >= 0; j--) {
mat[k][j] = d;
d++;
k++;
}
}
for ( k = 1; k < x; k++) {
i = m = k;
for ( j = x-1; j >= m; j--) {
mat[i][j] = d;
d++;
i++;
}
}
System.out.println("\n-----The matrix pattern-----\n");
for ( i = 0; i < x; i++) {
for(j = 0; j < x; j++) {
System.out.print(mat[i][j] + "\t");
}
System.out.print("\n");
}
}
}
Output
-----Enter the total number of rows-----
7
-----The matrix pattern-----
1 2 4 7 11 16 22
3 5 8 12 17 23 29
6 9 13 18 24 30 35
10 14 19 25 31 36 40
15 20 26 32 37 41 44
21 27 33 38 42 45 47
28 34 39 43 46 48 49