Deleted Thread

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.

I believe, you want something like this.
1
2
3
4
5
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?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <cstdio>
#include <iostream>
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.