Search code examples
javawhile-loopprime-factoring

While Loop Prime Numbers between 1 - 100


I'm pretty new to programming, and I'm trying to get my head around loops. I managed to get a piece of code working, but I'm still not fully understanding how it works. I found code for a similar program online which was written using a for loop and I managed to get it to work as a while loop (took me a few days!!!). I'm trying to understand what the inner loop is doing.

I know the outer loop is checking that x is less than 100 for each iteration of the loop. Why the need to nest the y variable in the loop, why is it set to 2 and why does it need to increment by one each time? Also, is there a way to get out of the loop without using the break; ?

I've seen a few other examples of this type of program here, but I am hoping someone can shed some light on how this one is working specifically.

Thanks in advance!!!

class PrimeNumbers {
  public static void main(String args[]) {
    int x = 2;
    while (x <= 100) {
      int y = 2;
      while (y <= x) {
        if (x == y) {
          System.out.println(x);
        }
        if (x % y == 0) {
          break;
        }
        y++;
      }
      x++;
    }
  }
}

Solution

  • Why the need to nest the y variable in the loop, why is it set to 2 and why does it need to increment by one each time?

    We need to reset the variable within the loop because the test needs to be applied for each value of x. The values of x are the potential candidates for prime numbers. Why is it set to 2 is because every number is divisible by 1.

    Also, is there a way to get out of the loop without using the break; ?

    You can add another condition to the second while loop. This flag could then be set once you exit condition has been satisfied.