简体   繁体   中英

Recursion and Stack in Java

I am working on stack and recursion. Let say I have a method like this:

public class RecursionStack {
    public String countIterative(int from, int to) {
        // do something? Use a loop?
    }
}

Can anybody help me like how can I return a string from the number given to the number given (using a loop?) So when I print out it will looks something like

System.out.print(RecursionStack.count( 5, 11 ));
prints: 5 6 7 8 9 10 11

Thank you very much!

Try this:

public class RecursionStack {
     public static String countIterative(int from, int to) {
         // the following if is your base case
         // and it is from here that you can stop 
         // performing recursion
         if (from == to) { return " " + to;}
         else { // this else is default and is the basis of the "recursiveness" of the function
             String toReturn = from + " " + countIterative(from+1, to);
             return toReturn;

         }

    }
}

A recursive method is one that calls itself. Also, you can't call a non-static method without an instance of the class. You could write an iterative version like,

public static void countIterative(int from, int to) {
    for (; from <= to; from++) {
        System.out.printf("%d ", from);
    }
}

and a recursive version like

public static void countRecursive(int from, int to) {
    if (from <= to) {
        System.out.printf("%d ", from);
        countRecursive(from + 1, to);
    }
}

and you might call them like

countIterative(5, 11);
System.out.println();
countRecursive(5, 11);
System.out.println();

and you would get the requested output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM