首页 > 解决方案 > 在 C 中的 2d 矩阵中的第二个对角线下打印元素

问题描述

您好我有一个代码显示二维矩阵的主对角线下的元素,我还需要显示第二个对角线下的元素。任何想法在循环中操作什么。

// loop to show the elements under the main diagonal
void element_under_diag(int number, int arr[number][number])
{
   int i, j;

   printf("\nUnder the main diagonal:\n");
      for(i=0;i<number;i++){
         for(j=0;j<number;j++){
            if(i>j)
               printf("%d ",arr[i][j]);
         }
      }
   printf("\n");

}

number在主函数中取自用户,它是矩阵中的行数和列数。

这个循环的结果是这样的:

The entered matrix is:
1 2 3
4 5 6
7 8 9
Under the main diagonal:
4 7 8

现在我需要输出是这样的:

The entered matrix is:
1 2 3
4 5 6
7 8 9
Under the secondary diagonal:
6 8 9

标签: cloopsmatrixmultidimensional-array

解决方案


如果一个数组是用 N * N 个元素定义的,那么 if 语句中的条件可能看起来像

if ( N - i - 1  < j ) printf( "%d ", a[i][j] );

推荐阅读