C Program to Print Matrix Pattern using For loop
ADVERTISEMENTS
C program to print matrix pattern using for loop. In this article, you will learn how to print numbers in matrix form in c language.
Source Code
// C Program to Print Matrix Pattern using For loop
#include <stdio.h>
int main() {
int x, i, j, k, d = 1, m;
// x - To store the number of rows
printf("-----Enter the total number of rows-----\n");
scanf("%d", &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++;
}
}
for ( i = 0; i < x; i++) {
for(j = 0; j < x; j++) {
printf("%d ", mat[i][j]);
}
printf("\n");
}
return 0;
}
Output
-----Enter the total number of rows-----
6
1 2 4 7 11 16
3 5 8 12 17 22
6 9 13 18 23 27
10 14 19 24 28 31
15 20 25 29 32 34
21 26 30 33 35 36