Java For Loop into Recursive function
14,551
Solution 1
Like so:
public class Recursive {
public void r(int i) {
if (i < 1024) {
i *= 2;
System.out.println("Count is: " + i);
r(i);
}
}
public static void main(String[] args) {
Recursive r = new Recursive();
r.r(1);
}
}
Solution 2
Take the loop of main
and put it in its own function with an argument int i
. In that function, rewrite the loop to
- If the loop condition is false (
i >= 1024
), thenreturn
- Else, recursive call with argument
i*2
.
Call the function with argument 1
or 2
, depending on which of your programs you're rewriting (they don't entirely match).
Solution 3
Recurrent loop can look like this:
class Main
{
public static void main(String[] args){
RecWhile(1);
}
public static void RecWhile(int i) {
if (i < 1024) {
i = i*2;
System.out.println("Count is: " + i);
RecWhile(i);
}
}
}
Author by
Paradox
Updated on July 23, 2022Comments
-
Paradox over 1 year
public class For { public static void main(String[] args){ for(int i=2; i<=1024; i *= 2){ System.out.println("Count is: " + i); } } public class While { public static void main(String[] args){ int i = 1; while (i < 1024) { i *= 2; System.out.println("Count is: " + i); } } public class DoWhile { public static void main(String[] args){ int i = 1; if (i < 1024) { do { i*=2; System.out.println("Count is: " + i); } while (i < 1024); } }
How would one convert the for loop/while loop so it does the same thing, but using a recursive function?
-
Ingo almost 13 years-1 for being not helpful. Enabling students to solve the problem at hand is helpful, to serve them the solution on a silver tray is not, IMHO. Why should Manpreet Pangli ever care listeing to his professor, when it's so cheap to get the answer from SO?
-
Lukasz almost 13 yearsIt produces different results than the examples in OPs question. Your program starts printing from 1. Multiplication by 2 should be done before println.
-
Lukasz almost 13 years@Ingo: I didn't know it's homework. There's no homework tag. I think it's not fair to -1 answers not because they are not correct, but they were given to "homework questions".
-
David Grant almost 13 years@Ingo: it's hard to argue against your point, although it is a little judgemental!
-
Lukasz almost 13 yearsThis answer is marked -1 not because it's incorrect, but BECAUSE it was given to a question that was not supposed to be answered this way (of course, that's not my POV; but the that's the way it is on Stack Overflow)
-
Ingo almost 13 yearsNo, that's me, not SO. If you do not see that this can only be homework, I can't help it.
-
Ingo almost 13 yearsYes, @David, I care about the next generation programmers, even if they're from India. And I can't stand it if people can get away with avoidance of thinking.