My assignment is to have the user input a number, and I take that number and perform the hailstone sequence on it. If it's even, divide by 2 and if it's odd, multiply by 3 and 1, and continue until the number is 1. I have written the code for the math part but am having trouble calling the function and displaying the numbers... Anyone see what I'm doing wrong? Sorry I'm still new
#include <cstdio>
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
int n;
cout <<"What number shall I start with? ";
cin >> n;
cout <<"The hailstone sequence starting at the number is: ";
cout << next(n);
return 0;
}
// **Computes the next number in the hailstone sequence
int next(int n)
{
int num=n;
while(num!=1)
{
if(num%2==0)
{
num=num/2;
}
else
{
num=(num*3)+1;
}
return num;
}
}
// **Writes entire hailstone sequence.
// **Finds the length of the hailstone sequence
// **Returns largest value in hailstone sequence
// **
#include <cstdio>
#include <iostream>
usingnamespace std;
// **Computes the next number in the hailstone sequence
int next(int n)
{
int num=n;
while(num!=1)
{
if(num%2==0)
{
cout << num << ", ";
num=num/2;
}
else
{
cout << num << ", ";
num=(num*3)+1;
}
}
}
int main(int argc, char** argv)
{
int n;
cout <<"What number shall I start with? ";
cin >> n;
cout <<"The hailstone sequence starting at the number is: ";
next(n);
return 0;
}
// **Writes entire hailstone sequence.
// **Finds the length of the hailstone sequence
// **Returns largest value in hailstone sequence
// **
Your original code is having trouble because you call next() before you define it. just add
int next(int n);
at the top of the program to tell the compiler that this function exists.
But the code seems to be confused about what next() really does. Does it compute the next value? or does it compute and print all values until the sequence terminates? Pick one and make the code do that.
Hmm:
1 2 3 4
// **Writes entire hailstone sequence.
// **Finds the length of the hailstone sequence
// **Returns largest value in hailstone sequence
// **
This indicates that you need to do more with the sequence, so I suggest something different:
1 2
// Return the hailstone sequence that starts with n and ends with 1.
vector<int> computeHailstone(int n);
If you write this function, then doing all the other things will be easy.