Ok so i have to write a program called hailstone numbers. Its basically asking the user to enter a number and if its even divide it by 2, if its odd multiply it by 3 and add 1 and then output the number of iterations. I made my program but I have a problem. The series keeps going and doesn't stop.

Here's my program -

#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
    int number = 0;
    int numIterations = 0;// number of iterations taken to reach 1
    
    cout << "Enter a number:" << endl;
    cin >> number ;
    
    while ( number != 1 ){
           while ( number % 2 == 0 ){
                 number = number /2;
                 cout << number << ", " << endl;
                 numIterations = numIterations + 1; 
                 }
                  while ( number % 2 != 0 ){
                        number = ( number * 3 ) + 1;
                        cout << number << ", " << endl;
                        numIterations = numIterations + 1;
                        }           
          }
          
  cout << "The number of iterations taken to reach 1 is " << numIterations << endl;         
  
    system("PAUSE");
    return EXIT_SUCCESS;
}

Edited 6 Years Ago by networkZombie: misspelt 'hailstone'

You just need to change your 2 inner while loops to if/else statements.

if( number % 2 == 0 )

on line 15
AND

else

on line 20

Good job, you're almost there.

Edited 6 Years Ago by Grn Xtrm: n/a

This question has already been answered. Start a new discussion instead.