Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to reverse an array of strings recursively?
    text
    copied!<p>supposed to reverse an array of strings recursively.</p> <p>having trouble implementing this. if i was using a for loop i would just start it at the end of the array and print out the array starting with the last element and ending with the first.</p> <p>I'm not too sure how to do it recursively. i was thinking about using a swap but that idea sort of fizzled when i couldnt figure out how to change the elements that i was swapping.</p> <p>any ideas or a push in the right direction would be appreciated.</p> <hr> <p>this is what icame up with so far. i know its wrong, i get an error out of bounds exception which im not sure how to fix. I think im not swapping the first and last correctly. but am i getting the right idea?</p> <p>this is what i came up with. a is an array. its inside a class.</p> <pre><code>// reverse an array public void rev() { rev(0,a.length-1); } private void rev(int first, int last) { if(last == 0) { //do nothing } else { while(first != last) { int temp = first; first = last; last = temp; System.out.print(" " + a[first]); rev((first + 1), (last - 1)); } } } </code></pre> <hr> <p>made some changes and it reverses the last 3 elements but the it repeats the second element. i have no if statement that controls when it runs so shouldnt it run until left = right?</p> <p>this is what i changed it to</p> <pre><code>// reverse an array public void rev() { rev(0,a.length-1); } private void rev(int first, int last) { if(last == 0) { //do nothing } else { String temp = a[first]; a[first] = a[last]; a[last] = temp; System.out.print(" " + a[first]); rev(first+ 1, last-1); } } </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