Ishwarya Deepak
Ishwarya Deepak

Reputation: 11

My While loop doesn't end even when the condition is met

So as an assignment I am trying to build a Collatz Conjecture program. My program works as expected, but the only problem is that it doesn't end when it reaches 1. Instead, the code loops and the program seem to start from the beginning in its own loop. Below attached is my code. Any help is much appreciated. Thank You!

while (n!=1){
  if ((n % 2) == 0) {
    n/=2;
    System.out.println(n);
  }
  if ((n % 2) > 0) {
    n*=3;
    n++;
    System.out.println(n);
  }
  n = n;
}

Upvotes: 1

Views: 297

Answers (2)

Asad Ali
Asad Ali

Reputation: 309

You should do it like this,the problem occurs because you updated your n in every condition and loop continue to run and that is why your program is not running.

int m=0;
while (n!=1){
        if ((n % 2) == 0) {
             m=n/2;
        System.out.println(m); 
       }
       if ((n % 2) > 0) {
           m=n*3;
           m++;
           System.out.println(m);
       }

       n = m;
 }

Upvotes: 0

Eran
Eran

Reputation: 393771

You are running both conditions in each iteration, so even if the first condition updates n to 1, the following condition immediately changes its value to becomes larger than 1 again.

You should only run the second condition's body if the first condition is false, which means you can transform the second condition to an else clause:

if ((n % 2) == 0) {
    n/=2;
    System.out.println(n);
} else {
    n*=3;
    n++;
    System.out.println(n);
}

Example:

Suppose n==2 - the first condition is true, and it modifies n from 2 to 1. Now, in the same iteration, the second condition becomes true, and n is multiplied by 3 and incremented by 1, so the loop doesn't end.

Upvotes: 3

Related Questions