hi
im kind of confused about how to change a for loop into a while loop and how to change a recursive into a for loop and for loop into a recursive, i read books and searched online but it all seems confusing
could somebody please simplify it for me?

thanx in advance.

;)
mina

Dani AI

Generated

A short, practical roadmap that ties the thread together: asked for simple conversions, and asked for specifics, and gave a clear tail-recursion → loop explanation using GCD. Below are concise, repeatable patterns and small examples not shown earlier.

for <-> while (mechanical)

  • A for(init; cond; step) { body } is equivalent to:

    init;
    while (cond) {
        body;
        step;
    }
  • The reverse moves the init and step into the for header. Example: iterate and sum 0..n-1.

    for (int i = 0; i < n; ++i) sum += i;

    becomes

    int i = 0;
    while (i < n) {
        sum += i;
        ++i;
    }

recursion <-> iteration (practical rules)

  • Tail recursion: convert by turning changing parameters into mutable locals and loop until the base case. Tail-recursive factorial with an accumulator becomes a simple loop:

    int factorial(int n) {
        int acc = 1;
        for (int i = n; i > 1; --i) acc *= i;
        return acc;
    }
  • Non-tail recursion (where the caller uses the returned result) requires either rewriting the algorithm (often possible) or simulating the call stack explicitly (use a stack/array). Tree traversals are a common example where an explicit stack replaces recursion.

for -> recursive (direct)

  • A simple for that visits indices can be written as a tail-recursive helper:

    void print_from(int i, int n) {
        if (i >= n) return;
        print(i);
        print_from(i + 1, n);
    }

C-specific cautions and debugging tips

  • The C standard does not guarantee tail-call optimization; do not rely on the compiler to eliminate deep recursion.
  • Common conversion bugs: wrong loop-exit condition, off-by-one in the update, forgetting to update all state variables, or losing the order of operations from recursive returns.
  • For large depths prefer iterative or an explicit stack for predictable memory use.

Recommended Answers

All 3 Replies

Is this in general, or do you have a loop that you want to change?

>could somebody please simplify it for me?
No, but we can help you to understand it better if you'll do more than offer vague references to general techniques.

Okay. Generally speaking, tail recursion (where the last thing to be executed is the recursive call) can be optimized to some kind of loop. Not necessarily a "for" loop. Here's a step by step process for doing it. We'll use the GCD example that lies in another thread. The greatest common divisor function, when defined recursively, looks like this:

int gcd(int x, int y)
{
    if (y == 0) {
        return x;
    }
    return gcd(y, x % y);
}

Now, the recursive call, gcd(y, x % y), can be interpreted as "Go back to the beginning of the function, with the new values for x and y being y and x%y, respectively."

So now we code that manually:

int gcd(int x, int y)
{
top: /* A label, used by the goto. */
    if (y == 0) {
        return x;
    }
    int param_1 = y; /* First assign to temporary variables */
    int param_2 = x % y;
    int x = param_1; /* Then set your 'new' values for x and y. */
    int y = param_2;
    goto top; /* Goto the top of the function. */
}

And the recursion has now been replaced by a loop. Further optimization can be done. For instance, if you carefully assign in the right order, only one temporary parameter holder is necessary.

int gcd(int x, int y)
{
top:
    if (y == 0) {
        return x;
    }
    int tmp = x;
    x = y;
    y = tmp % y;
    goto top;
}

It's not hard to see that this could be written as a while loop, which runs until y == 0:

int gcd(int x, int y)
{
    while (y) {
        int tmp = x;
        x = y;
        y = tmp % y;
    }
    return x;
}

Sometimes, you can't easily get rid of the goto (and then it's not worth eliminating the goto. But if we're going to talk about what is readable programming or not, we might as well leave in the tail-recursion and trust the compiler to optimize it away).

Now you can try to figure out on your own how to convert a loop to recursive form. It is similar to the reverse of this process.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.