0

Trying to print a 2D array diagonally, going right to down, other solutions I've found are going in the opposite direction

Example of what I'm trying to achieve:

Input:

0 1 2 3
1 2 3 4
2 3 4 5
3 4 5 6

Intended Output:

0 2 4 6
1 3 5
2 4
3

(and other side 1 3 5, 2 4, 3)

Managed to print a diagonal with

for (x=0; x<12; x++) {
    printf("%d ", arr[x][x])
}

But unsure how to replicate it for multiple, following attempt is incorrect

for (x=0; x<12; x++) {
    for (y=0;y<x+1;y++) {
        printf("%d ", arr[x][y]);
    }
    printf("\n");
}
EsmaeelE
  • 2,331
  • 6
  • 22
  • 31
TryingToLearn
  • 33
  • 1
  • 6

1 Answers1

0

The following C program meets your requirements. Try to understand the indexing.

int n, i, j, k;
int arr[5][5] = {
        0, 1, 2, 3, 4,
        1, 2, 3, 4, 5,
        2, 3, 4, 5, 6,
        3, 4, 5, 6, 7,
        4, 5, 6, 7, 8
};
n = 5;
for (k = 0; k < n; k++) {
    int ind = 0;
    for (i = k; i < n; i++) {
        printf("%d ", arr[i][ind++]);
    }
    printf("\n");
}

Output of the following program:

0 2 4 6 8 
1 3 5 7 
2 4 6 
3 5 
4 

You can change the size of the array and change the value of n, it will work for your desired n*n array.

Roy
  • 1,189
  • 7
  • 13