简体   繁体   中英

How do you traverse a 2D array diagonal in C?

I know how to traverse 2D array horizontal but how to I diagonal in C that is m by n? Similar to Java or no? Like this:

with

1 2 3 4
5 6 7 8
9 10 11 12

we get

1 6 11

Add 1 to both array indexes each time through the loop. Stop looping when m reaches width - 1 or n reaches height - 1.

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--]);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM