Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

# Thread: how to find all occurrences of a number in an array recursivelly

1. ## how to find all occurrences of a number in an array recursivelly

guys, given the fact I have an array how can I find all occurrences of the number recursively. I have figure out how to do a linear search recursively, but that would exit once it finds the number... what modification do I need to make in order to find all occurrences of the number.

```int[] nums = {20, 25, 29, 55, 25}

//search with recursion
public static int search(int[] a, int n, int i)
{
if(i == a.length-1)
return -1;
else if(a[i] == n)
return i;
else
return search(a, n, ++i);
}

search(nums, 25, 0);```

2. ## Re: how to find all occurrences of a number in an array recursivelly

Are you wanting to simply count them or return an array of all of their indexes?

3. ## Re: how to find all occurrences of a number in an array recursivelly

just count them...

4. ## Re: how to find all occurrences of a number in an array recursivelly

thought about it for a bit, and came up with answer, may not be the most efficient. If someone got a better implementation.. post

```static int count = 0, i = 0;
public static int displayOccu(int[] a, int n)
{
if(i == a.length)
return count;
else
{
if(a[i] == n)
{
i++;
count++;
return displayOccu(a, n);
}
else
{
i++;
return displayOccu(a, n);
}
}
}```

5. ## Re: how to find all occurrences of a number in an array recursivelly

There is a much better way of doing it, by taking the count variable out. This should also do it:
```public static int displayOccu(int[] a, int n, int i)
{
if(i == a.length)
return 0;
else if(a[i] == n)
return 1+displayOcc(a,n,i+1);
else
return displayOcc(a,n,i+1);
}```

This code is very similar to examples of summation with recursion. If the number is a hit, we add one and check the rest, otherwise we just check the rest. When it reaches the end of the array, it returns 0 to the previous call, and then adds together each 1 as the recursive call returns to where it was called.
I haven't compiled or tested the code, but in theory it should work.