`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()).

 ``1234`` ``````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.

I believe, you want something like this.
 ``12345`` ``````while (n != 1) { n = next(n); cout << n; }``````
Original question for reference purposes:
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?
 ``1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465`` ``````#include #include using namespace 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; } else if (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.
Topic archived. No new replies allowed.