Reputation: 3
I am having a problem with converting a while loop to a recursion ... the loop seems to work fine however I tried several times to turn it to recursion and what the method returns is the last (return c;) as 0 ... I mean how can you actually turn a while loop into a recursion? the program should count the numbers below 2 in the array
thats the main
public static void main(String[] args) {
double[] gpa = new double[]{2.5, 1.3, 1.3, 3.3, 1.2, 3.2, 4, 2.3, 3.1, 1.2};
int start = 0;
countGPA(gpa,start);
System.out.println(countGPA(gpa, start));
}
and thats the method
public static int countGPA(double[] gpas, int start) {
int L = gpas.length;
int c = 0;
int countGPA = c;
while (start < 10) {
if (start > 0 && start != L) {
if (gpas[start] < 2.0 && gpas[start] > 0) {
c++;
}
} else if (start == L) {
return 0;
} else if (start < 0 && start > L) {
return -1;
}
start++;
}
return c;
}
Upvotes: 0
Views: 955
Reputation: 337
Two important things to note when creating recursive methods.
In your scenario the recursion will stop when the index value is equal to the length of the array.
Anything that can be iterated over can also be a candidate for recursion.
Info on recursion: https://www.javatpoint.com/recursion-in-java
public int numbersBelowTwo(double[] gpas, int index){
//Base case, when this statement equates to true
//the recursions stops and returns the values.
if (index == gpas.length) return 0;
return gpas[index] < 2 ? 1 + numbersBelowTwo(gpas, ++ index) : numbersBelowTwo(gpas, ++index);
}
Upvotes: 0
Reputation: 79015
There are three most important things about a recursive function/method:
Do it as follows:
public class Main {
public static void main(String[] args) {
double[] gpa = new double[] { 2.5, 1.3, 1.3, 3.3, 1.2, 3.2, 4, 2.3, 3.1, 1.2 };
int start = 0;
System.out.println(countGPA(gpa, start));
}
public static int countGPA(double[] gpas, int start) {
return countGPA(gpas, start, 0);
}
public static int countGPA(double[] gpas, int start, int count) {
if (start >= gpas.length) {// Terminating condition
return count;
}
if (gpas[start] < 2.0 && gpas[start] > 0) {
return countGPA(gpas, ++start, ++count);// The recursive call
} else {
return countGPA(gpas, ++start, count);// The recursive call
}
}
}
Output:
4
Upvotes: 0
Reputation: 7724
This looks like a simple recursion:
public int GPA(double[] gpas, int index){
if(index >= gpas.length) return 0;
if(0 < gpas[index] && gpas[index] < 2) return 1 + GPA(gpas, index + 1);
else return GPA(gpas, index + 1);
}
Just call it GPA(gpa, 1)
.
There is a lot of unnecessary comparisons in your method. Look at your uses of 10
, L
and start
.
For example, suppose start = 0
. No one of your if
s will enter. Better to start with 1. Look:
if (start > 0 && start != L) //start is 0 so this won't enter
else if (start == L) //start is 0 so this won't enter
else if (start < 0 && start > L) //start is 0 so this won't enter
Upvotes: 1