Matrix Pattern in C++ language using For loop
ADVERTISEMENTS
Matrix pattern in c++ language using for loop. In this article, you will learn how to print the matrix pattern in c++ language using for loop.
Source Code
// Matrix Pattern in C++ language using For loop
#include <iostream>
using namespace std;
int main() {
int x, i, j, k, d = 1, m;
// x - denotes the number of rows
cout << "-----Enter the total number of rows-----\n";
cin >> x;
int mat[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++;
}
}
cout << "\n-----The matrix pattern-----\n\n";
for ( i = 0; i < x; i++) {
for(j = 0; j < x; j++) {
cout << mat[i][j] << " ";
}
cout << "\n";
}
return 0;
}
Output
-----Enter the total number of rows-----
5
-----The matrix pattern-----
1 2 4 7 11
3 5 8 12 16
6 9 13 17 20
10 14 18 21 23
15 19 22 24 25