I want to reverse and array of integer recursively, I think this is the way but I get this error when trying with a 5 integer array:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at name.of.package.ArrayAscDesc.CambioAscDesc(ArrayAscDesc.java:12)
at name.of.package.ArrayAscDesc.main(ArrayAscDesc.java:34)

Here's the code:

import java.util.Scanner;

public class ArrayAscDesc {

    public static int[] CambioAscDesc (int[] array, int index, int tam){
        while(index < tam){
            int temp = array[index];
            array[index] = array[tam];
            array[tam] = temp;
            CambioAscDesc(array, index++, tam--);
        return array;
    public static void main(String[] args) {
        Scanner teclado = new Scanner(System.in);
        System.out.print("Inserte el tamaƱo del array: ");
        int tam = teclado.nextInt();
        int[] array = new int[tam];
        System.out.println("Inserte datos para un array de " + tam + " elementos:");
        for(int i=0; i<tam; i++)
        {array[i]= teclado.nextInt();}
        System.out.print(CambioAscDesc(array, 0, tam));


Thanks beforehand!

Recommended Answers

All 5 Replies

The while on line 7 looks wrong to me. This is a recursive solution, it shouldn't need another loop. I would expect a simple if.
You'll probably want a better print on line 32, since array is an array.

Even changing it to an if I get the same error.

About the print, I needed to name it so I named it "array".

At the entry to your recursive method print the values of all the parameters so we can see where its going wrong.
To print the contents of the array you can use
System.out.println( Arrays.toString(array));

I have pretty much the same problem but what I need to do is a bit more complicated :/
I need to get an input like "Hello" and reverse it and the output has to be "o,lo,llo,ello,Hello"
please Help!

Forget the computer. Get a sheet of paper and work out how you would do this by hand. In detail. Then, and only then, write a program that does the same thing.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.