Given a Matrix 3x3 How can I traverse through the longest diagonal only?
Take this example:
1 2 3
4 5 6
7 8 9
I want to traverse through 1,5,9
Supposing your matrix is a 2D array called matrix
:
for (int i = 0; i < matrix.length; i++) {
// do something with entry matrix[i][i]
}
should be what you're looking for.
Creating a function where parameters are : the array, no of rows and no of columns. Thus we may recieve a diagonally persent values. Diagonally present values are those where the row and column index are same.
X . . . .
. X . . .
. . X . .
. . . X .
. . . . X
void diagonalPrint(int a[100][100], int noOfRows, int noOfCols)
{
for(int i=0; i<noOfRows && i<noOfCols ; i++)
{
printf("%d", a[i][i]);
}
}
Also, to print reverse diagonal, that is
. . . . . X
. . . . X .
. . . X . .
. . X . . .
. X . . . .
X . . . . .
void diagonalPrint(int a[100][100], int noOfRows, int noOfCols)
{
for(int i=0; i<noOfRows && noOfCols==0 ; i++)
{
printf("%d", a[i][noOfCols--]);
}
}