title: How to fix infinite loop in simple C++ function?
body: <p>I'm a beginner in C++ and the code is part of an assignment. I'm having problem with the program infinite looping. I know the infinite loop occurs in sequence(n), but I don't understand why it is infinite looping. I've evaluated the process step by step but I seem to be missing something.</p>
  
  <p>Ex: of a problem I am facing: n = 7, sequence prints: 7 22 22 22 22 22</p>
  
  <pre><code>#include &lt;cstdio&gt;
  using namespace std;
  
  // next(n) returns the value that follows n in the hailstone sequence.
  // Example: next(7) = 22, next(22) = 11, etc.
  // Since the hailstone sequence ends at 1, n is required to be &gt; 1.
  
  int next (int n)
  {
    while (n &gt; 1)
    {
      if (n%2 == 0)
      {
        return n/2;
      }
      else
      {
        return 3*n+1;
      }
    }
    return 1;
  }
  
  // sequence(n) executes next(n) in a loop to print the next integer(s)
  // in the hailstorm sequence, starting from n until ending with 1.
  
  void sequence(int n)
  {
    int nextNum = n, x = next(nextNum);
    while (nextNum &gt; 1)
    {
      printf("%i", nextNum);
      nextNum = x;
      break;
    }
    if (nextNum == 1)
    {
      printf("%i", 1);
    }
  }
  
  int main()
  {
    int n;
    printf("Enter n: ");
    scanf("%i", &amp;n);
  
    sequence(n);
  
    return 0;
  }
  </code></pre>