Converting one-dimensional to two-dimensional array

Hi guys. I had a hard question in my C++ final exam and I'm trying to solve it for the last 3 days. I haven't succeded yet! Here is the question: You have a one-dimensional array
 A[20]={1,2,3,4,...,20}
and B[5][4] you have to assign the A array's elements to the B array but there is an order which is:
 B[5][4] = { { 12, 9, 11, 10 }, { 14, 7, 13, 8 }, { 16, 5, 15, 6 }, { 18, 3, 17, 4 }, { 20, 1, 19, 2 } }
and there is a restriction: you can only use ONE for statement, nothing else! That's what I've done so far:
 ``123456789101112131415161718192021222324252627`` ``````#include #include using namespace std; int main(){ int A[20] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }; // define A array's elements. int B[5][4] = { 0 }, k = 1; // define B array and k counter. for (int i = 0; i < 5; i++){ // for statement: rows. for (int j = 0; j < 4; j++){ // for statement: columns. (j % 2 == 0) ? // check column. (B[i][j] = A[k + 10 - j / 2 + 2 * i], k += 2) : // column 0 and 2. (B[i][j] = A[k + (9 + j) / 2 - 2 * i], k -= 2); // column 1 and 3. } // end of for statement: columns. } // end of for statement: rows. for (int p = 0; p < 5; p++){ // first (rows) for statement to print B array. for (int q = 0; q < 4; q++) // second (columns) for statement to print B array. cout << setw(6) << B[p][q]; // print B array's elements. cout << endl; // new line after each row. } cout << endl; // new line after the array. return 1; // main function successfully ended. } ``````
I can't narrow the statements to one, any ideas how can we? P.S. This program works perfectly but it shouldn't be that long, we need ONLY ONE FOR statement, not two!..

Thank you!
Look for a pattern in the "specific order". You can easily do this with one for loop and no nesting.
Thank you. The problem is solved.
 ``1234567891011121314`` ``````#include int main(){ int A[20] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }, B[5][4] ; for (int i = 0; i < 10; i++){ (i <= 4) ? (B[4 - i][1] = A[2 * i], B[4 - i][3] = A[2 * i + 1]) : (B[i - 5][2] = A[2 * i], B[i - 5][0] = A[2 * i + 1]) ; } return 1; }``````

Special thanks to Deepak Kv.
Topic archived. No new replies allowed.