tags:

views:

45

answers:

2

for ex: let a 2-D array be

1 2 3 

2 3 5

7 8 9 

Then the output must be

1 2 3

  3 5

    9

Using simple for loops

i want the syntax.

+7  A: 

Do you mean that you want to print the upper triangular subset?

I suggest that you use a width specifier when you generate output (i.e. %4d for printf, cout << setw(4) << x; for iostreams) so that the alignment doesn't depend on the contents.

Then loop through your array and test whether you are in the upper triangle. If yes, output the value, if no, output spaces. When you reach the end of each row, output a newline character.

Ben Voigt
A: 

For a square matrix represented as 2D array

int arr[ N ][ N ];

an element

arr[ i ][ j ]  where 0 <= i < N and 0 <= j < N

is in upper diagonal if and only if

i <= j

is true.

So, the code can be something like

bool isElemInUpperDiagonal( int row, int column ) {
    return row <= column;
}

for( int i = 0; i < N; ++i ) {
    for( int j = 0; j < N; ++j ) {
        if( isElemInUpperDiagonal( i, j ) {
            cout << arr[ i ][ j ];
        }
        else {
            cout << " ";    // space for non upper diagonal
        }
        cout << " ";        // unconditional space
    }
    cout << "\n";           // newline after every row
}
ArunSaha