You are here:

C++/hailstone numbers

Advertisement


Question
i cant get my program to run correctly, it only prints out two numbers of the sequence, then stops.




#include "stdafx.h"

#include <iostream.h>

void exercise23()
{
  int iVal;
  int compOne;
  int SecNum;
  cout<<endl;
  cout<<"Enter a number that is greater than 1: ";
  cin>>iVal;
  cout<<endl;
  compOne = iVal;
  cout<<iVal<<", ";
  do
  {
     if (compOne%2 != 0)
     {
        SecNum = ((compOne*3)+1);
        cout<<SecNum<<", ";
        compOne = SecNum;
     }
     if (compOne%2 == 0)
     {
        SecNum = compOne/2;
        cout<<SecNum<<", ";
        compOne = SecNum;
     }
  }while(compOne == 1);
}

int main(int argc, char* argv[])
{
  exercise23();
  return 0;
}

Answer
Reid,
I'm not sure what you're trying to accomplish with this program. What is it calculating? Also, how many times is it supposed to run? I changed the code (just a little bit), and it would print out anywhere from 2 to 4 numbers in the sequence. Here is the slightly modified code that I used:

//Include Statements
#include <iostream.h>

//Exercise Function
void exercise23()
{
  int iVal;
  int compOne;
  int SecNum;
  
  cout << "\nEnter a number that is greater than 1: ";
  cin>>iVal;
  cout<<endl;
  compOne = iVal;
  cout<<iVal<<", ";
  
  //Do-While loop
  do
  {
     if (compOne%2 != 0)
     {
        SecNum = ((compOne*3)+1);
        cout<<SecNum<<", ";
        compOne = SecNum;
     }
     if (compOne%2 == 0)
     {
        SecNum = compOne/2;
        cout<<SecNum<<", ";
        compOne = SecNum;
     }
  } while(compOne == 1);
}

//Main Program
void main() {
  exercise23();
}

If you could provide me with more info I could help you more.

Alan

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Alan F.

Expertise

Having problems with any basic or intermediate parts of C++? I can answer those questions for you using simple English. I have been taking C++ in school for a couple years, so I still remember what it was like to be a beginner (especially with C++, which is a difficult language)!

Experience

I have a C++ web page that discuses the basics of C++. The address is: http://www.afweb.net/complang/

©2016 About.com. All rights reserved.