Recursive alternative for a counter.

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?
first remark you forgot the return type of the function

this is a normal recursion //no need here for counters
1
2
3
4
5
6
int HailstoneLength(int n){
       if(x != 1)
             return 1+HailstoneLength(Hailstone(x));   //like count++
       else
             return 1;    //if x=1
}


this is a tail recursion version //more efficient on most modern compilers which optimise them so there is no function call
1
2
3
4
5
6
int HailstoneLength(int n,int count=1){
       if(x != 1)
             return HailstoneLength(Hailstone(x),count+1);
       else
             return count;
}


for a better version of tail recursion (more user friendly):
1
2
3
4
5
6
7
8
9
int HailstoneLength(int n){
       return HailstoneLength(Hailstone(x),1);
}
int HailstoneLength_2(int n,int count=1){
       if(x != 1)
             return HailstoneLength_2(Hailstone(x),count+1);
       else
             return count;
}
Topic archived. No new replies allowed.