3

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.

2
  • What you want as output? The position of the searched number? Commented Jan 24, 2016 at 21:47
  • 2
    I think instead of passing cont++ you would still need to pass y, and increment cont++ separately, before calling searchR(y) in your else condition Commented Jan 24, 2016 at 21:51

2 Answers 2

2

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);

        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot, this is exactly what i was looking for! It works as it should now.
@LeinadDC Happy to know that "this is exactly what you were looking for". If so then mark this as accepted answer.
2
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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.