Nov 30, 2015 at 7:49pm UTC
I'm trying to use a counter in this recursive function below and it doesn't seem to be counting each time but only once. Why is it doing this and how can I fix it? Thanks!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
int lengthOJP (int D) {
int count = 1;
if (D == 1) { // Base case
count++; // Counter
cout << "count = " << count << endl;
} else if ((D % 2) != 0) { // odd numbers
D = ((D * 3) + 1); // if D is odd
count++;
lengthOJP(D); // Recursive Call
} else { // even
D /= 2;
count++;
lengthOJP(D);
}
return count;
}
Last edited on Nov 30, 2015 at 9:11pm UTC
Nov 30, 2015 at 7:56pm UTC
And just how are you returning count from nested calls?
Nov 30, 2015 at 9:10pm UTC
I had return at the end of the function and it didn't (code edit) do anything. Where should I put it?
Nov 30, 2015 at 9:14pm UTC
That will return the count to the caller.
What does the caller do with the value?
Hint: lines 13 and 19 ignore the return value.
Nov 30, 2015 at 9:35pm UTC
Ohhh okay I see! I didn't realize I wasn't passing count on the the next iteration call of the function, it works now, thank you!
Last edited on Nov 30, 2015 at 9:35pm UTC