# Help needed to turn a recursive method into iterative

• 07-16-2010, 03:41 PM
mercyfulfate
Help needed to turn a recursive method into iterative
Hi there! I'm in need of a bit of help, I'm going crazy with some Java practice I have to do.

I need to turn this recursive method (cal):

public class Recursivo {

private int valores[] = {12, 13, 25, 34, 56, 75, 16, 78, 11, 65, 89};

public int cal (int a, int b)
{
int i = (a+b)/2;
if (a<=b) {
return (valores[i]%2) + cal(a, i-1) + cal(i+1, b);
}
else {
return 0;
}
}
}

into a non recursive (iterative) method that does the same thing.

Anyone can spare some time to help me out?

Thanks!
• 07-16-2010, 04:27 PM
Norm
Do you have a description of what the app does?
• 07-16-2010, 05:05 PM
mercyfulfate
Nope, sorry. I was given that code as it is and asked to change it so it does the same thing without using recursivity :(
• 07-16-2010, 05:07 PM
Norm
A description of what it does could help you find another way to code it.
• 07-16-2010, 07:01 PM
mercyfulfate
Believe me or not, you just made me solve the problem :D

I tried to understand the purpose of that method for the n-th time and finally found the reasoning behind it (it returns how many odd numbers are stored in the array between 2 given positions (the method params a & b)).

So...

public int cal2 (int a, int b)
{
int total = 0;

if (a<=b){
for (int i=a;i<=b;i++){
total+= valores[i]%2;
}