Actually you should break the function down first:

A loop has a few parts:

  1. the header, and processing before the loop. May declare some new variables

  2. the condition, when to stop the loop.

  3. the actual loop body. It changes some of the header's variables and/or the parameters passed in.

  4. the tail; what happens after the loop and return result.

Or to write it out:

foo_iterative(params){
    header
    while(condition){
        loop_body
    }
    return tail
}

Using these blocks to make a recursive call is pretty straightforward:

foo_recursive(params){
    header
    return foo_recursion(params, header_vars)
}

foo_recursion(params, header_vars){
    if(!condition){
        return tail
    }

    loop_body
    return foo_recursion(params, modified_header_vars)
}

Et voilà; a tail recursive version of any loop. breaks and continues in the loop body will still have to be replaced with return tail and return foo_recursion(params, modified_header_vars) as needed but that is simple enough.


Going the other way is more complicated; in part because there can be multiple recursive calls. This means that each time we pop a stack frame there can be multiple places where we need to continue. Also there may be variables that we need to save across the recursive call and the original parameters of the call.

We can use a switch to work around that:

bar_recurse(params){
    if(baseCase){
        finalize
        return
    }
    body1
    bar_recurse(mod_params)
    body2
    bar_recurse(mod_params)
    body3
}


bar_iterative(params){
    stack.push({init, params})

    while(!stack.empty){
        stackFrame = stack.pop()

        switch(stackFrame.resumPoint){
        case init:
            if(baseCase){
                finalize
                break;
            }
            body1
            stack.push({resum1, params, variables})
            stack.push({init, modified_params})
            break;
        case resum1:
            body2
            stack.push({resum2, params, variables})
            stack.push({init, modified_params})
            break;
        case resum2:
            body3
            break;
        }
    }
}
Answer from ratchet freak on Stack Exchange
Top answer
1 of 2
49

Actually you should break the function down first:

A loop has a few parts:

  1. the header, and processing before the loop. May declare some new variables

  2. the condition, when to stop the loop.

  3. the actual loop body. It changes some of the header's variables and/or the parameters passed in.

  4. the tail; what happens after the loop and return result.

Or to write it out:

foo_iterative(params){
    header
    while(condition){
        loop_body
    }
    return tail
}

Using these blocks to make a recursive call is pretty straightforward:

foo_recursive(params){
    header
    return foo_recursion(params, header_vars)
}

foo_recursion(params, header_vars){
    if(!condition){
        return tail
    }

    loop_body
    return foo_recursion(params, modified_header_vars)
}

Et voilà; a tail recursive version of any loop. breaks and continues in the loop body will still have to be replaced with return tail and return foo_recursion(params, modified_header_vars) as needed but that is simple enough.


Going the other way is more complicated; in part because there can be multiple recursive calls. This means that each time we pop a stack frame there can be multiple places where we need to continue. Also there may be variables that we need to save across the recursive call and the original parameters of the call.

We can use a switch to work around that:

bar_recurse(params){
    if(baseCase){
        finalize
        return
    }
    body1
    bar_recurse(mod_params)
    body2
    bar_recurse(mod_params)
    body3
}


bar_iterative(params){
    stack.push({init, params})

    while(!stack.empty){
        stackFrame = stack.pop()

        switch(stackFrame.resumPoint){
        case init:
            if(baseCase){
                finalize
                break;
            }
            body1
            stack.push({resum1, params, variables})
            stack.push({init, modified_params})
            break;
        case resum1:
            body2
            stack.push({resum2, params, variables})
            stack.push({init, modified_params})
            break;
        case resum2:
            body3
            break;
        }
    }
}
2 of 2
2

Following up on @ratchet freak's answer, I created this example of how the Fibonacci function can be rewritten to a while loop in Java. Note that There's a much simpler (and efficient) way to rewrite the Fibonacci with a while loop though.

class CallContext { //this class is similar to the stack frame

    Object[] args;

    List<Object> vars = new LinkedList<>();

    int resumePoint = 0;

    public CallContext(Object[] args) {
        this.args = args;
    }

}


static int fibonacci(int fibNumber) {
    Deque<CallContext> callStack = new LinkedList<>();
    callStack.add(new CallContext(new Object[]{fibNumber}));
    Object lastReturn = null; //value of last object returned (when stack frame was dropped)
    while (!callStack.isEmpty()) {
        CallContext callContext = callStack.peekLast();
        Object[] args = callContext.args;
        //actual logic starts here
        int arg = (int) args[0];
        if (arg == 0 || arg == 1) {
            lastReturn = arg;
            callStack.removeLast();
        } else {
            switch (callContext.resumePoint) {
                case 0: //calculate fib(n-1)
                    callStack.add(new CallContext(new Object[]{arg - 1}));
                    callContext.resumePoint++;
                    break;
                case 1: //calculate fib(n-2)
                    callContext.vars.add(lastReturn); //fib1
                    callStack.add(new CallContext(new Object[]{arg - 2}));
                    callContext.resumePoint++;
                    break;
                case 2: // fib(n-1) + fib(n-2)
                    callContext.vars.add(lastReturn); //fib2
                    lastReturn = (int) callContext.vars.get(0) + (int) callContext.vars.get(1);
                    callStack.removeLast();
                    break;
            }
        }
    }
    return (int) lastReturn;
}
Top answer
1 of 2
2

Think of a for loop as a little anonymous function that takes the loop index value as a parameter. In order to start the next iteration of the loop, the function can return a call to itself with a new value for the loop index parameter.

Like this:

Object loop(int i, Object data) {
    if (i > 0) {
        return loop(i - 1, evolve(data));
    } else {
        return data;
    }
}

That's the same as this:

for ( ; i > 0; i--) {
    data = evolve(data);
}

In some languages, particularly Scheme, and who knows maybe Java 8 or 9, the compiler is guaranteed to compile a recursive function such as the function loop above just the same as it compiles the for loop above.

In other languages, including the current and past versions of Java, nearly all compilers will make an executable that builds a big call stack. When the call stack is large it may even overflow the permitted size and crash the program.

2 of 2
2

Haters aside, let's do this! [1]

Given:

int x = 3;
for (int i = 0; i < x; i++) {
  for (int j = 0; j < x; j++) {
    for (int k = 0; k < x; k++){
      list.add(array[i] + array[j] + array[k]);
    }
  }
}

Let's consider that each loop is it's own recursive function - as this makes the recurrence cases much easier! This is also the only "non-thinking" method I know of to turn the loops into recursion. The recursive depth will be limited to 3*x => i+j+k so it's "fairly safe" for a smallish[2] x.

In Java it requires a separate method for each loop to encode this structure. (In a language with higher-order functions these three functions might be abstractly combined .. but not in Java [7].)

void loopI(int i) {
    if (i < x) {
      loopJ(0);   // "start j loop"
      loopI(i++); // "next i loop" / recurrence case
    }
    // "end loop" / base case
}

void loopJ(int j) {
    if (j < x) {
      loopK(0);
      loopJ(j++);
    }
}

void loopK(int k) {
   if (k < x) {
     list.add(array[i] + array[j] + array[k]);
     loopK(k++);
   }
}

// do it!
loopI(0); 

All of these could be combined into a single recursive function, but that makes handling the recurrence cases a bit tougher as "thinking" and additional conditionals (or mod expressions, perhaps) are required to advance the state.

Here is an example of a combined recursive function (this is incorrect when x is 0). Unlike the three method approach above, the stack depth will grow to x^3 => i*j*k. This will easily kill Java's recursion limits - even for smallish values of x- as Java [7] doesn't have tail-call optimization.

void loop(int i, int j, int k) {        
    list.add(array[i] + array[j] + array[k]);

    // advance states
    k++;
    if (k == x) { k = 0; j++; }
    if (j == x) { j = 0; i++; }
    if (i == x) { i = 0; }

    // terminate on all wrap-around
    if (i == 0 && j == 0 && k == 0) { return; }

    // recurse
    loop(i, j, k);
}

[1] YMMV, for theoretical purposes only - I love recursion, but it's not suited for this case in Java.

[2] For some value of "smallish". See how deep your stack can go!

Discussions

Transfer for loop to recursion, Java - Stack Overflow
I need to transfer for loop to recrusion function.. This is my fucntion: public void AddEnemyToScreen(int enemy_count) { for(int i=0 ; i More on stackoverflow.com
🌐 stackoverflow.com
java - For loop to Recursion - Stack Overflow
How would i convert the for loop in the method to recursion, i've tried using if else but that just goes on forever and crashes import java.io.*; import java.util.*; public class Combinations { More on stackoverflow.com
🌐 stackoverflow.com
java - converting while loop to recursion - Stack Overflow
I am having a problem with converting a while loop to a recursion ... the loop seems to work fine however I tried several times to turn it to recursion and what the method returns is the last (retu... More on stackoverflow.com
🌐 stackoverflow.com
May 20, 2020
java - Convert Recursion to Loop or another faster solution - Stack Overflow
This is part of the code works very fast in c++, but for now, need to convert into Java, but straight converting into Java code led to taking more time... So, for now looking for improvement of existing code. Upd. D - depth, L1 - amount of {}, L2 - amount of [] and L3 - amount of (). More on stackoverflow.com
🌐 stackoverflow.com
🌐
Reddit
reddit.com › r/learnjava › convert for loop to a recursive function
r/learnjava on Reddit: convert for loop to a recursive function
September 30, 2020 -

can Someone help me convert this iterative function into a recursive function?

public int getMax(int [] A, int i, int j){

int max = A[i];

for (int k = i+1; k <=j ; k++) {

if(A[k]>max){

max = A[k];

}

}

return max;

}

I do not really understand recursion. I know the function will call itself at some point, but i'm pretty confused still.

Top answer
1 of 1
2
When writing recursive functions one of the first things you should think about is how you are going to make the recursion stop, i.e. what are your base cases? This is analogous to thinking about your exit conditions in a loop. In this example your base case is the same as your for loops stopping point, you want to exit when some counter, k, is greater than or equal to j. Each recursive call will need to modify the k variable in a similar way as the for loop is modifying it with each iteration, k++. You also need to think about what you want to do when you actually hit your base case, in this instance you want to return the max value. some pseudo code to get you started: public int getMax(int[] A, int i, int j, int k, int max){ // note the changes to the function signature // base cases // if k > j, return max; -- found the max, return it // else // find max so far: if (A[k] > max) max = A[k]; // recurse by calling getMax with the next k value and the new max, and returning the result of that recursive call // return getMax(...) } I assume this is a homework problem, if you're allowed to change the variable names it would be nice to change i to "start" and j to "end" and k to "i" since i is traditionally used for the current index, and would make reading the code a bit more clear. Recursion can be hard to grasp at first, try working through the code step by step, literally writing down the variable values for each function call and what they will return. You'll notice that one function is kindof "paused" when it calls itself and you have a new set of variables to work through. Once you finally "bottom out" and hit the base case that doesn't recurse, all your function calls will start "rubberbanding" back their return values upwards until the original function call itself returns.
🌐
Quora
quora.com › How-would-you-convert-a-recursion-into-a-for-loop
How would you convert a recursion into a for loop? - Quora
This is always can be translated into a loop relatively directly. The algorithms than use the recursion massively are often rewritten in a dif ... It depends. Formally you can always convert a recursion to a while cycle if you have a stack-like structure to emulate the recursion.
🌐
Refactoring
refactoring.com › catalog › replaceIterationWithRecursion.html
Replace Iteration with Recursion - Refactoring
Formal methods folks use the term "loop-invariant" to describe the condition that exists as the result of each iteration. An invariant can be added to code as either comments or assertions. The use of good identifier names can often reduce the need for this type of comment. But in the example above, there are no appropriate identifiers to name -- and do you really want to introduce a temp? The solution is to replace the iteration with recursion...
🌐
Stack Overflow
stackoverflow.com › questions › 71685839 › for-loop-to-recursion
java - For loop to Recursion - Stack Overflow
How would i convert the for loop in the method to recursion, i've tried using if else but that just goes on forever and crashes · import java.io.*; import java.util.*; public class Combinations { private static String str; public static void main (String args[]) { Scanner scan = new Scanner(System.in); System.out.println("Enter string: "); str = scan.nextLine(); combine(str); } private static void combine(String str){ for(int j = 0; j < str.length(); j++){ String temp = ""; for(int i = j; i < str.length(); i++){ temp += String.valueOf(str.charAt(i)); System.out.println(temp); } } } }
Find elsewhere
Top answer
1 of 3
1

This looks like a simple recursion:

public int GPA(double[] gpas, int index){
    if(index >= gpas.length) return 0;

    if(0 < gpas[index] && gpas[index] < 2) return 1 + GPA(gpas, index + 1);
    else return GPA(gpas, index + 1);
}

Just call it GPA(gpa, 1).

There is a lot of unnecessary comparisons in your method. Look at your uses of 10, L and start.


For example, suppose start = 0. No one of your ifs will enter. Better to start with 1. Look:

if (start > 0 && start != L)     //start is 0 so this won't enter

else if (start == L)             //start is 0 so this won't enter

else if (start < 0 && start > L) //start is 0 so this won't enter
2 of 3
0

There are three most important things about a recursive function/method:

  1. The terminating condition.
  2. The value with which the method/function is called recursively.
  3. Where (before/after the recursive call) to process the parameter(s).

Do it as follows:

public class Main {
    public static void main(String[] args) {
        double[] gpa = new double[] { 2.5, 1.3, 1.3, 3.3, 1.2, 3.2, 4, 2.3, 3.1, 1.2 };
        int start = 0;
        System.out.println(countGPA(gpa, start));
    }

    public static int countGPA(double[] gpas, int start) {
        return countGPA(gpas, start, 0);
    }

    public static int countGPA(double[] gpas, int start, int count) {
        if (start >= gpas.length) {// Terminating condition
            return count;
        }
        if (gpas[start] < 2.0 && gpas[start] > 0) {
            return countGPA(gpas, ++start, ++count);// The recursive call
        } else {
            return countGPA(gpas, ++start, count);// The recursive call
        }
    }
}

Output:

4
🌐
Stack Overflow
stackoverflow.com › questions › 49390635 › convert-recursion-to-loop-or-another-faster-solution
java - Convert Recursion to Loop or another faster solution - Stack Overflow
Will be another way to make this method faster? recursion: public static int MOD = 11380; public static int[][][][] memo = new int[11][11][11][31]; static int ret; public static int solve(int L1, int L2, int L3, int D) { if (D < 0) { return 0; } if (L1 + L2 + L3 == 0) { return 1; } ret = memo[L1][L2][L3][D]; if (ret == 0) { // ret = 0; for (int i = 0; i < L1; ++i) { for (int j = 0; j <= L2; ++j) { for (int k = 0; k <= L3; ++k) { ret += solve(i, j, k, D - 1) *solve(L1 - 1 - i, L2 - j, L3 - k, D); ret %= MOD; } } } for (int i = 0; i < L2; ++i) { for (int j = 0; j <= L3; ++j) { ret += solve(0, i, j, D - 1) * solve(L1, L2 - 1 - i, L3 - j, D); ret %= MOD; } } for (int i = 0; i < L3; ++i) { ret += solve(0, 0, i, D - 1) * solve(L1, L2, L3 - 1 - i, D); ret%= MOD; } } return ret; }
🌐
Quora
quora.com › How-do-you-convert-iterative-code-to-recursive
How to convert iterative code to recursive - Quora
Answer (1 of 5): Here the iterative code to find the factorial of a given number. [code]n=5 res=1 for i in range(n,0,-1): res*=i print(res) [/code]Output: 120 To convert the iterative code to recursive code , first you need to find the terminating condition which end the function call and the...
Top answer
1 of 2
1

So this is not pretty, but it works without recursion. Also i changed the return type from double to int because of reasons:

public static int sum(int z, int x, int y)
{
    // Compute number of calls
    int[][] calls = new int[x+1][x*y+1];
    calls[0][0] = 1;
    for (int i = 0; i < x; i++) {
        for (int j = 0; j <= x*y; j++) {
            for (int target = j+1; target <= j+y && target <= x*y; target++) {
                calls[i+1][target] += calls[i][j];
            }
        }
    }

    // Return count of last column where z <= 0
    int result = 0;
    for (int j = x*y; z-j <= 0; j--) {
        result += calls[x][j];
    }
    return result;
}

To understand, have a look at this high-tech Excel sheet:

This chart illustrates a call of sum(3, 3, 3). Horizontally you see x and vertically you see z both get smaller. y is 3 and not changed.

The top left 1 means one call to sum(3, 3, 3). This call then spawns three child calls (because of y=3): sum(2, 2, 3), sum(1, 2, 3) and sum(0, 2, 3). These three calls are found in the next column (where x=2).

Each of those three calls then spawns again three calls, shown in the row of x=1. These nine calls overlap a bit regarding z. Each of those nine calls then spawns again three calls, resulting in 27 calls in the x=0 column.

To get the result, you simply count all calls in the x=0 column, where z <= 0. In this example this is every call, so you get a result of 27. For a larger z the result would be smaller.

2 of 2
0
public static double sum(int z, int x, int y) {
    int num = 0;    
    for (int i = 0; i <= y; i++) {
        if (z - x - i > 0) {
            num++;
        }
    }

    return (double) (Math.pow(y, x) - num);
}

Explanation: your method launches at most y^x recursive calls. On the last level of recursion, where x == 0, you have to determine the max value of z throughout all the calls and check how many of these calls do have z > 0, so that the call returns 0 and you do not have to take it into account. Now, on the last level of recursion, the max value of z is given by z - x. You now simply count all the instances in the for loop for which z - x stays positive so it does not influence your sum. After you computed that number, substract it from the initial approximation of the result, which was y^x.

🌐
Stack Overflow
stackoverflow.com › questions › 72065588 › turn-a-for-loop-into-recursion
java - Turn a for loop into Recursion - Stack Overflow
Base case - that represents a simple edge-case (condition when recursion terminates) for which the outcome is known in advance. In for this task, the base case will represent a situation when the source list was discovered completely and position is equal to its size (invalid index).
Top answer
1 of 2
1

BASIC PROBLEM

They don't "go back to their old state" -- those variables are destroyed (released back to the memory heap) when you exit the method instance.

Those are local variables -- allocated when you enter the method, released on exit; some are input parameters, and receive their initial values from the arguments to the call. Thus, they don't "go back to their old state". What you're seeing is the unchanged states from the previous instance of the method.

Each time you call the routine, you add another instance to the stack. Each instance has its own version of the variables, which happen to share names. They do not share values.

SOLUTION

You work around this by keeping to basic principles of modular programming: you pass values into a method with the parameter list; you get values back with the return list. For instance, your final else clause might look something like this:

child_result = recurs(j1, index1, index2, indexTab1,
                      tab1, tab2, tab3, nZeros,
                      cost, i, tab1Index, b);
tools.add(child_result);
return tools;

I have not read your code for functionality; you may well need something other than tools.add(child_result) to accumulate the proper values. However, I believe that I've given you the basic principle that's currently giving you trouble.

2 of 2
0

The problem was coming from pointers, the variables i used as parameters only stayed changed for the method and came back to their old state when it ended. I bypassed this by setting the variable as static class variables, and resetting them when i wanted to, but the solution from Prune looks better and less messy.

🌐
Open Computing Facility
ocf.berkeley.edu › ~shidi › cs61a › wiki › Iteration_vs._recursion
Iteration vs. recursion - CS 61A Wiki
An iterative function can be converted to a tail recursive function by using the loop condition as the base case and the body of the loop as the recursive step.
🌐
Jct
danzig.jct.ac.il › java_class › recursion.html
Java Recursion with examples
To convert this to tail recursion we need to get all the multiplication finished and resolved before recursively calling the function. We need to force the order of operation so that we are not waiting on multiplication before returning.
🌐
Stack Overflow
stackoverflow.com › questions › 53122414 › recursion-using-for-loop
java - Recursion using for-loop - Stack Overflow
public class Calc { public static void main(String[] args) { Scanner sc = new Scanner(System.in); double k = sc.nextDouble(); double e = sc.nextDouble(); double q = sc.nextDouble(); int n = sc.nextInt(); for (int i = 0; i < n; i++) { k = (k + (i * e)) * (1 + q); //The problem I have is that I don't know how to access the previous element of the for-loop } } } ... You say you should recursion, but I don't see any method that could be called recursively.