cress
cress

Reputation: 409

Looking in array method

I need guidance in understanding recursion.

Here is what I have:

public class ArrayMember
{
    public static void main(String[] args)
    {
        int index = 0;
        int [] arr = {1, 5, 6, 2};

        System.out.println(member(arr, index));
    }

    public static String member(int [] arr, int index)
    {
        if(index == arr.length)
            return str;

        str = index + "\t" + str + "\n";

        return str + member(arr, index+1);
    }
}

As you can see, this will never go all the way up to 20 and always prints "No". And I'm pretty sure having a for loop defeats the purpose, but I can't think of any other way to do it. Any help would be appreciated.

Upvotes: 0

Views: 52

Answers (1)

tobias_k
tobias_k

Reputation: 82899

There are two problems with your code:

  1. By setting str in each iteration of your loop, even if you find the element in position i, you overwrite str with "No" when there is a different element in position i+1, effectively setting str to whether the element is the last element in the array. Try to break from the loop once you find the value, or initialize str to "No" by default and only set it to "Yes" if you find it.
  2. By checking index == arr.length you are not testing all the numbers from 1 to 20. You could instead check whether index > arr[arr.length-1], i.e. check whether it's greater than the last element in the list, but this will only work if the list is sorted.

This should fix your code. However, to be honest I think you misunderstood the assignment a bit (although I have to admit that it is not very clear to start with). Instead of using recursion to test the subsequent numbers (with the problem that you do not really know when to stop), and using a loop to test the different positions of the array, I would reverse it: Use a loop to test the different numbers you want to test, and use recursion for the different positions in the array.

This way, you can simplify your program to this (Pseudocode):

function member(arr, num, index) -> bool :
    if index does not exceed array
        return arr[index] equals num or member(arr, num, index+1)
    else 
        return false

arr = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}
for i from 1 to 20
    print i, member(arr, i, 0)

Upvotes: 3

Related Questions