infinite while loop

Hello, can someone help me understand why this goes into an infinite loop? I

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
void collatzIterative(int n)
{
  
  while (n > 1)
    {
      
      if (n % 2 == 0)
	{
	  n /= 2;
	  cout << n << " ";
	 
	}
      
      if (n % 2 == 1)
	{
	  n = 3 * n + 1;
	  cout << n " ";
 
	}
    }
  
  cout << 1;
  
}


when I print n each time it changes, It prints '4 2 1 4 2 1 4 2 1...' once n = 1 shouldn't it get out of the loop?

Thanks!
Last edited on
closed account (D80DSL3A)
once n = 1 shouldn't it get out of the loop?

Yes. If only n made it to the end of the loop with that value, but it does not.
n becomes 1 in the 1st if code. This makes it enter the 2nd if code and it emerges with n = 4.
The while(n > 1) part never sees n = 1.

EDIT: Try else if instead for the 2nd code. It should work then.
Or just else. This because if n%2 != 0 then n%2 = 1.
Last edited on
Topic archived. No new replies allowed.