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
Hi Reid.
I am extremely sorry for the delay, but I am in middle of my exams and hence couldn't help.

The only thing wrong with the program is the while condition.
Instead of while(compOne==1) it should be
         while(compOne!=1)

Initilly, compOne is never 1, because the value user enters is greater than 1. So, if you say
         while(compOne==1)
The loop will run "as long as" compOne==1,which is not the case.Hence you get only one iteration of the loop(since you have used do while, atleast one iteration has to be there).

When I change it to while(compOne!=1), then it will run
"as long as" compOne!=1, and will stop when it is 1. This is what we want.

Here is the correct program:

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


Bi.
Samarth

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Samarth Bartaria

Expertise

I can answer questions about pointers behaviour, their implementations and anamolous behaviour.Also, I speciallize in object oriented design and modelling,polymorphism in C++ and algorithm efficiency. Even questions related to database design,or simple basics about programming are welcome.

Experience

I have been using C++ for five years now for software development and scientific analyses.

Organizations
Currently, I am a student doing my computer engineering.

©2016 About.com. All rights reserved.