I'm trying to learn something about recursion so I'm tryin' to do some exercises but now I'm kind of stucked because I can't figure out why does this function always return me 1 or 0 Im trying to count number of appearences of 11 in int array.
public class Uloha06 {
public static int count = 0;
public static int array11(int[] nums, int index){
if(index<nums.length){
if(nums[index]==11)
count+=1;
index++;
array11(nums,index);
if(index<nums.length)
return index;
}
return count;
}
public static void main(String[] args) {
int array11[]={11,1,2,36,11};
System.out.println(array11(array11, 0));
}
}
It returns 0
for an empty array, and 1
for a non-empty array. The result you see came from index
, not from count
as you are expecting.
I would write it without a field involved.
public int m(int[] nums, int index, int count) {
return index < nums.length ?
m(nums, index + 1, nums[index] == 11 ? ++count : count) :
count;
}
or (suggested by @Pshemo in the comments)
public int m(int[] nums, int index) {
return index < nums.length ?
(nums[index] == 11 ? 1 : 0) + m(nums, ++index) :
0;
}