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;
}

Recommended Answers

All 4 Replies

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.

No problem, glad to help :)

thanks was not enough lol ... that helped a lot :D

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.