I recently completed a HailstoneSequence program I was assigned. In this this program we had to prompt the user for an integer and display the Hailstone sequence starting at that integer, the sequences length, the number of odd numbers in the sequence, the largest number in the sequence, and the length of the longest sequence starting at the given integer. We were asked to do this assignment using loops.
We have been assigned this program again, but we have to use recursion for everything except calculating the next number in the sequence and displaying the sequence to the screen. I've been having trouble with methods that use count variables because of the count variable re initializing every time a function passes the next number in the sequence back to itself. Here is an example of my HailstoneLength() using loops.
1 2 3 4 5 6 7 8 9
HailstoneLength(int n){
int x = n, count = 1;
while(x != 1){
count++;
x = Hailstone(x); //other code
}
return count;
}
In my recursive assignment I tried following the same process by using the base case if(x=1) return count;, increment the count variable, and then pass the next number in the sequence back to the function but the count variable is initialized every time back to 1. Our instructor said we are not allowed to use global variables so is there another way to set up a counter when using recursion?