Zabe - 3 months ago 14

C++ Question

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.

Answer

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).