【问题标题】:Printing elements under second diagonal in 2d Matrix in C在 C 中的 2d 矩阵中的第二个对角线下打印元素
【发布时间】:2020-01-29 20:35:43
【问题描述】:

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

// 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

【问题讨论】:

标签: c loops matrix multidimensional-array


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    请在你的程序中替换:

    if(i>j)   // above the diagonal
    

    if( (i+j) >= N )   // below the diagonal
    

    【讨论】:

      【解决方案3】:

      条件我们无用,因为它可以通过循环直接完成:

      #include <stdio.h>
      void main(){
          int arr[3][3] = {1,2,3,4,5,6,7,8,9};
          element_under_diag(3,arr);
          element_under_secondary_diag(3,arr);
      }
      
      void element_under_diag(int number, int arr[number][number])
      {
         printf("\nUnder the main diagonal:\n");
            for(int i=1;i<number;i++){
              for(int j=0;j<i;j++){
                  printf("%d ",arr[i][j]);
               }
            }
         printf("\n");
      }
      
      void element_under_secondary_diag(int number, int arr[number][number])
      {
         printf("\nUnder the secondary diagonal:\n");
            for(int i=1;i<number;i++){
              for(int j=0;j<i;j++){
                  printf("%d ",arr[number-j-1][i]);
               }
            }
         printf("\n");
      }
      

      【讨论】:

        【解决方案4】:

        我设法以这种方式解决了它:

        // 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 secondary diagonal:\n");
              for(i=1;i<number;i++){
                 j = number - i; //Every time the row number goes up one, the starting column goes down one. 
                   for(;j<number;j++){
                    printf("%d ",arr[i][j]);
                 }
        
              }
           printf("\n");
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-22
          • 1970-01-01
          • 1970-01-01
          • 2016-06-02
          • 1970-01-01
          相关资源
          最近更新 更多