I have a matrix with n*n dimensions. For given integer k I have to print elements from diagonals.
From picture: for k=0, it has to print a vector: 1,12,23,34
.
How do i do this?
I have a matrix with n*n dimensions. For given integer k I have to print elements from diagonals.
From picture: for k=0, it has to print a vector: 1,12,23,34
.
How do i do this?
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' );
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])
}