Select to view content in your preferred language

Question: Recursion is used in Java to reverse an array.

405
1
Jump to solution
01-17-2023 12:37 AM
hectorsalamanca
New Contributor III

I'm just getting started with recursion, and while studying this article, I was able to utilise it to construct a basic factorial programme without any difficulty. I'm now attempting to construct a recursive function that writes an array in reverse order, but I'm not sure what I'm doing wrong. What am I overlooking? Thank you very much.

import java.io.*;

public class Recursion {
  public static void main(String[] args) throws IOException{
    int myArray[] = {1,2,3,4,5,6,7,8,9,10};
  }

  public static void reverseDisplay(int[] ary, int position){
    if(position > 0)
      System.out.print(ary[position]);
     reverseDisplay(ary, position - 1);
  }
}
Tags (1)
0 Kudos
1 Solution

Accepted Solutions
JohannesLindner
MVP Frequent Contributor
  1. You're not calling the function in your main
  2. You get an infinite recursive loop, because you keep calling the function even if position < 0
import java.io.*;

public class Recursion {
  public static void main(String[] args) throws IOException{
    int myArray[] = {1,2,3,4,5,6,7,8,9,10};
    reverseDisplay(myArray, 9);
  }

  public static void reverseDisplay(int[] ary, int position){
    if(position > 0) {
      System.out.print(ary[position]);
      reverseDisplay(ary, position - 1);
    }
  }
}

 


Have a great day!
Johannes

View solution in original post

1 Reply
JohannesLindner
MVP Frequent Contributor
  1. You're not calling the function in your main
  2. You get an infinite recursive loop, because you keep calling the function even if position < 0
import java.io.*;

public class Recursion {
  public static void main(String[] args) throws IOException{
    int myArray[] = {1,2,3,4,5,6,7,8,9,10};
    reverseDisplay(myArray, 9);
  }

  public static void reverseDisplay(int[] ary, int position){
    if(position > 0) {
      System.out.print(ary[position]);
      reverseDisplay(ary, position - 1);
    }
  }
}

 


Have a great day!
Johannes