LeinadDC
LeinadDC

Reputation: 73

Java Recursion help needed

I've been asked to create a public method that does nothing but to call another method that is recursive. The purpose of the second method is to search for a Int value inside an array.

So far I have this:

int[] array = {1, 2, 3, 7, 8, 11, 20, 30, 50, 100};
int cont = 0;

public int searchI(int x) {
    searchR(x);
    return x;
}

private void searchR(int y) {
    if (cont < array.length) {
        if (array[cont] == y) {
            System.out.println(y);
        } else {
            searchR(cont++);   
        }
    }
}

However, no matter what number I use, either one in the array or not, it always prints the value of y. I'm still new to recursion and not quite grasping the essence of it yet. That's probably why my method isn't working (besides that it is wrong). Any thoughts? And probably, help to grasp the term better.

Upvotes: 3

Views: 84

Answers (2)

kaveh.n
kaveh.n

Reputation: 243

static final int [] array={1,6,2,7,3,9,5};
 public static void searchI(int x)
{
    System.out.println(x);
    System.out.println(searchR(x,0));
}

   private static int searchR(int x,int _index)
{
    if(_index>array.length)
        return -1;
    else if(array[_index]==x)
        return _index;
    else
        return searchR(x,++_index);
}

Upvotes: 2

Shafi
Shafi

Reputation: 1970

As far you code, this will print y when it finds y in the array because of

if (array[cont] == y) {
     System.out.println(y);
}

And after first call of searchR(x) it is searching the value of cont instead of value of x. Change searchR(cont++) to

cont++; 
searchR(y);

If you want the position of the number you're searching use System.out.println(cont) instead of System.out.println(y).

int[] array = {1, 2, 3, 7, 8, 11, 20, 30, 50, 100};
int cont = 0;

public int searchI(int x) {
    searchR(x);
    return x;
}

private void searchR(int y) {
    if (cont < array.length) {
        if (array[cont] == y) {
            System.out.println(y); //System.out.println(cont); if you want the position as output
        } else {
            cont++;
            searchR(y);

        }
    }
}

Upvotes: 2

Related Questions