-4

I have a matrix with n*n dimensions. For given integer k I have to print elements from diagonals.

enter image description here

From picture: for k=0, it has to print a vector: 1,12,23,34.

How do i do this?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335

2 Answers2

1

A straightforward approach can look the following way

#include <stdio.h>

#define N   4

int main(void) 
{
    int a[N][N] =
    {
        {  1,  2,  3,  4 },
        { 11, 12, 13, 14 },
        { 21, 22, 23, 24 },
        { 31, 32, 33, 34 }
    };

    int k; 

    printf( "Select a diagonal (%d, %d): ", -N, N );

    scanf( "%d", &k );

    if ( k < 0 )
    {
        for ( int i = -k, j = 0; i < N; i++, j++ )
        {
            printf( "%d ", a[i][j] );
        }
    }
    else
    {
        for ( int i = 0, j = k; j < N; i++, j++ )
        {
            printf( "%d ", a[i][j] );
        }
    }

    putchar( '\n' );

    return 0;
}

The program output might look like

Select a diagonal (-4, 4): 2
3 14 

or

Select a diagonal (-4, 4): -2
21 32

Or instead of the if-else statement with separate loops you can use one loop as for example

int i = k < 0 ? -k : 0;
int j = k > 0 ? k : 0;

for ( ; i < N && j < N; i++, j++ )
{
    printf( "%d ", a[i][j] );
}

putchar( '\n' );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • For a new Comer I'll say that SO is not a Tutorial Site, but how can I tell you this? :) – Michi Oct 17 '17 at 21:11
  • @Michi Why is not it a tutorial site? I consider it as a tutorial site. Answering questions I am learning programming.:) – Vlad from Moscow Oct 17 '17 at 21:12
  • I think that more than 80% here will be agree with me. Who knows maybe I'm wrong :). This kind of Question is not a SO Question anyway. – Michi Oct 17 '17 at 21:14
  • @Michi Maybe. I'm not a specialist on questions in SO. As for me then each question has something interesting and new for me especially taking into account that I never have a C++ job.:) – Vlad from Moscow Oct 17 '17 at 21:20
-1

pseudo code:

function(martrix, k){
    rowmax = matrix.length;
    colmax = matrix[0].length;
    output = []
    for i = 0 to max(rowmax, colmax):
        if k > 0 : x = i + k
        if k < 0 : y = i + k
        if(x < rowmax and y < colmax):
            output.append(matrix[x][y])

}
Evol
  • 1
  • 2