John C.
John C.

Reputation: 445

Printing elements under second diagonal in 2d Matrix in C

Hello I have a code that shows the elements under the main diagonal of 2d matrix and I need to also show the elements under the second diagonal. any ideas what to manipulate in the loop.

// 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 is taken from the user in the main function and it's the number of row and columns in the matrix.

this loop result into an output like this:

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

Now I need the output to be something like this:

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

Upvotes: 1

Views: 3742

Answers (4)

myxaxa
myxaxa

Reputation: 1381

condition is useless due it can be done strait through the loop:

#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");
}

Upvotes: 1

John C.
John C.

Reputation: 445

I managed to solve it this way:

// 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");
}

Upvotes: 0

lenik
lenik

Reputation: 23528

Please, replace in your program:

if(i>j)   // above the diagonal

with

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

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

If an array is defined with N * N elements then the condition in the if statement can look like

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

Upvotes: 1

Related Questions