# Thread: Help needed to turn a recursive method into iterative

1. Member
Join Date
Jul 2010
Posts
3
Rep Power
0

## 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!

2. Do you have a description of what the app does?

3. Member
Join Date
Jul 2010
Posts
3
Rep Power
0
Nope, sorry. I was given that code as it is and asked to change it so it does the same thing without using recursivity :(

4. A description of what it does could help you find another way to code it.

5. Member
Join Date
Jul 2010
Posts
3
Rep Power
0
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;
}
}
else
return 0;
}

Thanks a lot! :D

6. Congratulations.
A question sparked an inspiration.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•