How do you write the following as two nested loops?
Code:for (int low = 0, high = n - 1; low < high; low++, high--)
How do you write the following as two nested loops?
Code:for (int low = 0, high = n - 1; low < high; low++, high--)
It can't be written as nested loops without totally changing what it does.
It is by nature a single-dimensional loop.
Why do you think you want a double loop?
Last edited by john.c; 07-14-2021 at 11:10 AM.
A little inaccuracy saves tons of explanation. - H.H. Munro
General rule: for is only a clever way to write while loops. With your example:
Is the same as:Code:for (int i = 0, j = n - 1; i < j; i++, j--) doSomething();
Code:/* block, because i and j are local to the loop */ { int i = 0, j = n - 1; while ( i < j ) { doSomething(); i++, j--; } }
I don't think you want that as two loops, because that would change the behavior in ways you don't expect. However, you could factor the "high" variable out as a function of the "low" variable:
Code:for (int low = 0; low < n / 2; ++low) { int high = n - 1 - low; // etc. }