int next (int n)
n is passed by value to next, meaning that any changes made to n within next() will not affect the original, even if the variables have the same name(parameter n and local variable n declared in main()).
1 2 3 4
while (n != 1)
{
cout << next(n);
}
You also haven't updated n, when you call next, so as long as you pass in a number to hailstoneSequence() that isn't -1, it will continue looping.
Hello, I'm writing a program that displays the hailstone sequence for the inputted value int n. I'm new to c++ and don't quite understand why I'm getting an infinite loop in the hailstoneSequence function. What I'm trying to do in that function is to simply loop the 'next' function until its value is just 1, thus ending the hailstone sequence itself.
An example of correct output if I input 7 would be...
7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
My program will only print
7 and then forever print 222222222222222222....... and so on.
I also don't understand how to record / print a found next(n) value, and then move on via next loop cycle. Can somebody provide insight for my problem?
#include <cstdio>
#include <iostream>
usingnamespace std;
// next(n)
// This function will take in an int value n and will return an int value
// that follows n in the hailstone sequence.
// This function requires n to be greater than 1.
int next (int n)
{
if (n == 1)
{
return n=1;
}
elseif (n % 2 == 0) // if even.
{
return n/2;
}
else // if not even, it's odd.
{
return 3 * n + 1;
}
}
// hailstoneSequence (n)
// This function will receive an int value n from main to compute the hailstone sequence.
// Requirement: next(1) must not be computed.
void hailstoneSequence (int n)
{
if (n == 1) // Prevents the computation of next(n) in case the value 1 is entered.
{
return;
}
else
{
// Keep looping until the value 1 is achieved.
// Goal: To repeat the function call for next(n)
// until the while loop's condition is considered true.
while (n != 1)
{
cout << next(n);
}
}
}
int main(int argc, char** argv)
{
int n;
cout << "What number shall I start with? ";
cin >> n;
cout << "The hailstone sequence starting at " << n << " is: " << n << " ";
hailstoneSequence(n);
cout << " " << endl;
}
This forum is a reference resource - the answer makes no sense without context.
The problem and proposed solution can be useful to others who are learning C++, that's why this forum is here.