This is kind of a misleading title but I didn’t know what to call it. But what I wanted here to print each and every “diagonal” of this grid in both the left and right direction. For example, if left to right, then we’ll have

And we’ll print

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


Approach

We’re going to divide this problem into two subproblems. In the first subproblem, we’ll print the diagonals starting from the cells in the first column below.

In the second subproblem, we’ll print the remaining diagonals starting from the cells in the first row but skipping the first overlapping element with the first column since we did that in the first subproblem.

First Subproblem

We’ll iterate over the first column. From the first cell, we’ll print the following diagonal.

Next, we’ll move to the next cell in the column and print the diagonal starting from it.

And finally the last cell in the column.

This is process is captured in the following code:

// left to right direction in an m by n grid
for (int i = 0; i < m; i++) {
    int k = i;
    int j = 0;
    // print the diagonal
    while (k < m && j < n) {
        printf("%d\t", a[k][j]);
        k++; j++;
    }
    printf("\n");
}

The above code will output

1 6 11
5 10
9


Second Subproblem

We’ll iterate over the row column starting at the second cell and print the diagonal from there.

We’ll move on to the third cell and print the diagonal again.

Finally, we’ll print the very last diagonal.

This process is captured in the following code:

for (int j = 1; j < n; j++) {
    int s = j;
    int i = 0;
    // print the diagonal
    printf("d: ");
    while (i < m && s < n) {
        printf("%d\t", a[i][s]);
        i++;
        s++;
    }
    printf("\n");
}

which will print the following

2 7 12
3 8
4


The Right to Left Direction

What about the complete other direction (right to left) below. How do we print these diagonals?

We’ll do the same thing, divide the problem into two subproblems and tackle each separately. This is captured in the following code:

// right to left
for (int i = 0; i < m; i++) {
    int k = i, j = 0;
    while (k >= 0 && j < n) {
        printf("%d ", a[k][j]);
        k--;
        j++;
    }
    printf("\n");
}
for (int j = 1; j < n; j++) {
        int i = m - 1, s = j;
        while (i >= 0 && s < n) {
            printf("%d ", a[i][s]);
            i--;
            s++;
        }
        printf("\n");
    }