用 C 语言程序对角线向下打印矩阵。
给定大小为 n x n 的数组,任务是打印整数类型矩阵的对角线向下元素。
对角线向下表示打印任意大小 n x n 的数组中对角线向下的元素,如下面的图所示 −
首先它将打印 1,然后移动到 2 并打印,并对角线向下移动到 4 并打印,等等。
实例
Input: Matrix [3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }} Output: 1 2 4 3 5 7 6 8 9
算法
int diagonally_down(int mat[n][n]) START STEP 1: DECLARE i, j, row, col AS INT STEP 2: LOOP FOR i = 0 AND i < n AND i++ SET row = 0 SET col = i LOOP WHILE col >= 0 PRINT mat[row][col] INCREMENT row BY 1 AND DECREMENT col BY 1 END WHILE END FOR STEP 3: LOOP FOR j = 1 AND j < n AND j++ SET row = j SET col = n-1 LOOP WHILE row < n PRINT mat[row][col] INCREMENT row BY 1 AND DECREMENT col BY 1 END WHILE END FOR STOP
实例
#include <stdio.h> #define n 3 int diagonally_down(int mat[n][n]){ int i, j, row, col; //printing above elements for (i = 0; i < n; i++){ row = 0; col = i; while(col >= 0) //Moving downwards from the first row{ printf("%d ", mat[row++][col--]); } } //printing below elements for (j = 1; j < n; j++){ row = j; col = n-1; while(row<n) //Moving from the last column{ printf("%d ", mat[row++][col--]); } } } int main(int argc, char const *argv[]){ int mat[][n] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; diagonally_down(mat); return 0; }
输出
如果运行上面的程序,它将生成以下输出 −
1 2 4 3 5 7 6 8 9
广告