Code for Hailstone sequence

Hi, I need help writing the code for a hailstone sequence using a recursive function. So far, I've managed to make a program that outputs the sequence perfectly based on the integer that the user inputs. However, at the end of the program I'm supposed to write the number of steps it took for the sequence to get to 1. How would I incorporate a counter in this program?
Thanks :)
ps. I tried incrementing a counter every time n changes but dunno where i would output counter... also the counter wasn't incrementing past 1, so i must've done something wrong...

#include <iostream>
using namespace std;

int hailstone (int n) {

if (n == 1)
{
return 1;
}

else {

if (n%2 != 0) {
n = 3*n + 1;
cout << n << endl;
}
else {
n = n/2;
cout << n << endl;
}
return hailstone(n);
}

}

int main (){
int N = 0;
cout << "Input an integer: ";
cin >> N;
cout << "The updated values of n are: \n";
return hailstone(N);
}
You could pass a counter thru as a parameter.

For example:
1
2
3
4
5
6
7
int hailstone(int n, unsigned& counter) {
    if (n == 1)
        return 1;

    ++counter;
    // ... the remaining implementation
}


And you start it with:
1
2
3
4
5
int main() {
    // ...
    unsigned counter = 0;
    hailstone(n, counter);
}
Last edited on
Topic archived. No new replies allowed.