Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java For Loop into Recursive function

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?

like image 213
Paradox Avatar asked Sep 27 '26 18:09

Paradox


2 Answers

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);
    }
}
like image 78
David Grant Avatar answered Sep 29 '26 08:09

David Grant


Take the loop of main and put it in its own function with an argument int i. In that function, rewrite the loop to

  1. If the loop condition is false (i >= 1024), then return
  2. 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).

like image 25
Fred Foo Avatar answered Sep 29 '26 08:09

Fred Foo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!