Zabe
Zabe

Reputation: 15

How do I write a loop function as a recursive function?

Well, I've been trying to rework this many times. Though, at one point I thought the longestSequence function would help, since it displays the longest hailstone sequence. Though, I can't seem to figure out how to find, or store the value it used to find that.If someone could explain how, I would appreciate it.

int longestSequence(int n)
{
    int u = n;

    if(u == 1)
    {
        return 1;
    }
    else 
    {
        return max(hailstoneLength(u), longestSequence(u-1));
    }
}

The part I'm having trouble with is my longest start sequence:

int hailLongestSeq(int n)
{
    int k;
    int longest = 0;
    for(int j = 1; j <= n; j++)
    {
        if(hailstoneLength(j) > longest)
        {
            longest = hailstoneLength(j);
            k = j;
        }
    }
    return k;   
}

I'm not sure how to make this into a recursion, I noticed for some recursions I saw people using for loops still, but I was sure we weren't supposed to use loops. It may be a dumb question, but is there a formula to translating for loops to recursions, if anyone knows one?

The expected out put is like this:

The longest hailstone sequence starting with a number up to 10 has length 20. The longest hailstone sequence starting with a number up to 10 begins with 9.

as 9's sequence has a length of 20 numbers, and is the longest from 1 to 10.

Upvotes: 0

Views: 3704

Answers (2)

Rishabh Kumar
Rishabh Kumar

Reputation: 557

You can add the local variables who's value you want to retain in the parameter signature of the function. I have tried to rewrite the code as recursive. Check and verify if this solves your problem.

int hailLongestSeq(int n, int j, int k, int longest)
{
    if(j <= n)
    {
        if(hailstoneLength(j) > longest)
        {
            longest = hailstoneLength(j);
            k = j;
        }
        k = hailLongestSeq(n, ++j, k, longest);
    }
    return k;   
}

This may need a fix, however the logic remains the same, pass the variables as parameter to retain the value.

Upvotes: 0

Jean-Baptiste Yun&#232;s
Jean-Baptiste Yun&#232;s

Reputation: 36401

Yes every for loop can be translated to recursive call, obviously like this:

for (i=0; i<N; i++) {
  body;
}

translate it to:

func(int i) {
  if (i<N) { body; func(i+1) }
  else return;
}

func(0);

This can be easily extended to any for loop computation (add parameters if needed, return value, etc).

Upvotes: 4

Related Questions