Program to find all indices using recursion not working

package recursion;

public class allIndicesInArray {
public static void main(String args[]) {

	int arr[]= {3,8,7,8,9};
	System.out.println(allIndices(arr, 0, 8, 0));
}

public static int[] allIndices(int[] arr, int si, int data, int count) {
	
	if(si==arr.length) {
		int[] base= new int[count];
		return base;
	}
	int [] indices = null;
	if(arr[si]==data) {
		indices = allIndices(arr, si+1, data, count+1);
	}else {
		indices = allIndices(arr, si+1, data, count);
	}
	
	if(arr[si]==data) {
		indices[count]=si;
	}
	return indices;
}

}

Hey @jeevika32_7f86c13248dfa5c9,
The code is logically correct.
You are returning an array and directly trying to print it.
So, you are getting the address of the array as the output.
In order to print the returned array we need to capture it in a variable and then iterate over it.

int[] rr = allIndices(arr, 0, 8, 0);
for(int i=0;i<rr.length;i++){
System.out.println(rr[i]);
}

Here’s your updated code>
Hope it helps

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.