Is there a way to store values diagonally from a matrix?
E.g.
a b c d
e f g h
i j k l
m n o p
output string:
minejoafkp...
is it possible to be done in a single nested loop?
Is there a way to store values diagonally from a matrix?
E.g.
a b c d
e f g h
i j k l
m n o p
output string:
minejoafkp...
is it possible to be done in a single nested loop?
Is using a simple nested loop an absolute requirement? I can think of one way to do this, but it involves a second array containing the coordinates of interest from the first array.
If your array is of fixed size then Matticus's suggestion is probably best for its simplicity.
If your array can be any size, but is a square array, then the following seems to work.
It could presumably be generalized to rectangular arrays.
Code:#include <stdio.h> #define SIZE 5 int main(void) { char m[SIZE][SIZE] = { {"AFJMO"}, {"6BGKN"}, {"37CHL"}, {"148DI"}, {"0259E"} }; for (int i = SIZE; i-- > 0; ) for (int row = i; row < SIZE; row++) putchar(m[row][row-i]); for (int i = SIZE; i-- > 0; ) for (int row = 0; row < i; row++) putchar(m[row][row+SIZE-i]); putchar('\n'); return 0; }
It can be done with a single loop (not nested) if you're willing to add a few more variables and some if statements to control how the "cursor" walks
Code:#include <stdio.h> #define SIZE 5 int main(void) { char m[SIZE][SIZE] = { {"AFJMO"}, {"6BGKN"}, {"37CHL"}, {"148DI"}, {"0259E"} }; int start = SIZE, col = 0, row = SIZE; for (int i = 0; i < SIZE*SIZE; i++) { if (row == SIZE && start > 0) { row = --start; col = 0; } else if (col == SIZE) { col = ++start; row = 0; } putchar(m[row++][col++]); } return 0; }
Last edited by algorism; 03-31-2016 at 08:05 AM.