Hi there, I recently got an assignment to create an algorithm for hailstone numbers. I've managed to complete most of it however I'm having an issue when it comes to the output. My code does not output all the hailstone numbers and the loop stops to soon.
#include <iostream>;
usingnamespace std;
int main() {
int input_counter=0;
int n;
cout << "Please a number: "<<endl;
cin >> n;
while (input_counter <= n) {
if (n % 2 == 0)
{n = n/2;
cout<<n<<endl;}
if (n % 2 == 1)
{n = (n*3) + 1;
cout<<n<<endl;}
input_counter = input_counter + 1;
}
return 0;
}
I know the issue is with my 10th line of code, I've tried changing it to (input_counter < 1000000), and that outputs all the number but the loop never ends. I'm having trouble finding a way to end the loop and output all the hailstone numbers including 1.
First I would change your second if (line 16) to an else if. See if that helps.
Second, what exactly do you want the looping condition to be? It's not clear. Show an example of input and output you want.
If you want an input of, say, n = 12 to output (12) 6 3 10 5 16 8 4 2 1,
then your loop condition should be while (n != 1) { ... }
If you want to stop iterating after a certain number of iterations, then do while (n != 1 && input_counter <= max_iterations) where max_iterations is some constant of your choosing.
^^^ Listen to this. New coders sometimes get into a habit of putting extra ;s in. The ;s are harmless, mostly. But the habit is very bad.
you will, if you keep doing this, end up doing things like:
1 2 3 4 5 6
if (something);
this_always_happens(); //but you thought it was in the if, didn't you?
or this:
for(x = 0; condition, x++);
this_happens_once(); //you thought it was in the loop, didn't you?
compilers warn about these goofs if cranked up on warnings but new coders don't do that either :P combine the two and you will have some 'fun' stuff to debug late at night before its due.