Hi,
I am trying to use recursion and count to find the number of times the number 5 appears in an array. I have the following code:
public static int countfive(double[] array1, int beginarray, int endarray,int count)
{
int next;
if(beginarray==endarray)
{
if(array1[startIndex]==5)
return 1;
else
return 0;
}
else
{
if(array1[beginarray]==5)
{
count=count+1;
System.out.println("COUNT ONE"+count);
next=countNegative(array1,beginarray+1,endarray,count)+startIndex;
}
else if(array1[beginarray]!=5)
{
System.out.println("COUNT TWO"+count);
next=countNegative(array1,beginarray+1,endarray,count);
System.out.println("THIS IS BEGIN ACCESSED");
}
}
System.out.println("VALUE"+count);
return count;
}
I have tested this code on a set of numbers, and i get the following:
If i enter:
1
2
3
4
5
5
6
5
The following output occurs:
COUNT TWO0
COUNT TWO0
COUNT TWO0
COUNT TWO0
COUNT ONE1
COUNT ONE2
COUNT TWO2
COUNT ONE3
COUNT TWO3
THIS IS BEGIN ACCESSED
VALUE3
VALUE3
THIS IS BEGIN ACCESSED
VALUE2
VALUE2
VALUE1
THIS IS BEGIN ACCESSED
VALUE0
THIS IS BEGIN ACCESSED
VALUE0
THIS IS BEGIN ACCESSED
VALUE0
THIS IS BEGIN ACCESSED
VALUE0
I am not sure why the count value is being subtracted and how i can prevent that from happening so i can just return the correct value ?