You are here:

# C++/hailstone numbers

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

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

Alan
Questioner's Rating
 Rating(1-10) Knowledgeability = 10 Clarity of Response = 10 Politeness = 10 Comment Thanks for responding. I tried the microsoft sight and even they couldn't find my answer for me, kept shifting me around. I tried emailing the author of the book, unfortunately they have not responded yet. Thanks anyway, I will find a solution somehow. :)

C++

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/