Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Yes. This can be performed by recursive programming.</p> <p>I assume you do not like to WRITE DOWN these nested for's in source code - as in your example, because this is really ugly programming - like the commentors explain.</p> <p>The following (pseudo Java-like) code illustrates it. I assume a fixed depth for the nesting. Then you actually like to loop over an integer vector of dimension depth.</p> <pre><code>int[] length = new int[depth]; int[] counters = new int[depth]; </code></pre> <p>The array <code>counters</code> has to be initialised to 0 (<code>Arrays.fill(counters,0)</code>). The array <code>length</code> has to be initialised to the number of iterations for the respective for loop.</p> <p>I assume that you like to perform a certain operation within the inner loop. I will call this <code>performOperation(int[] counters);</code> - it depends on the multi-dimensional counter, i.e. the counters of the outer for's.</p> <p>Then you can run the nested for loops by calling</p> <pre><code>nestedLoopOperation(counters, length, 0); </code></pre> <p>where</p> <pre><code>void nestedLoopOperation(int[] counters, int[] length, int level) { if(level == counters.length) performOperation(counters); else { for (counters[level] = 0; counters[level] &lt; length[level]; counters[level]++) { nestedLoopOperation(counters, length, level + 1); } } } </code></pre> <p>In your case your System.out.println() would be</p> <pre><code>performOperation(int[] counters) { String counterAsString = ""; for (int level = 0; level &lt; counters.length; level++) { counterAsString = counterAsString + counters[level]; if (level &lt; counters.length - 1) counterAsString = counterAsString + ","; } System.out.println(counterAsString); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload