3 Replies Latest reply: Mar 27, 2013 5:08 PM by 999443

# Trouble Understanding Logic of Primes Program

I am reading a book called Beginning Java 7, by Ivor Horton. In his book he has a primes calculation program. The code is below. I am having trouble understanding the logic of the program. I've stared at it for the past several hours with no luck. What I can't understand is how both i and j are both initialized to 2 but the if statement:
``````if(i%j == 0) {
continue OuterLoop;
}``````
then passes a 2 to the println() function. I am totally lost on this problem. The program below outputs all of the prime numbers from 2 to 50 without any errors. Please help!
Thank you.
``````public class Primes2 {
public static void main(String[] args) {
int nValues = 50;                                                  // The maximum value to be checked

// Check all values from 2 to nValues
OuterLoop:
for(int i = 2 ; i <= nValues ; ++i) {
// Try dividing by all integers from 2 to i-1
for(int j = 2 ;  j < i ; ++j) {
if(i%j == 0) {                                                 // This is true if j divides exactly
continue OuterLoop;                                          // so exit the loop
}
}
// We only get here if we have a prime
System.out.println(i);                                           // so output the value
}
}
}``````
Edited by: EJP on 27/03/2013 19:54: fixed all the bizarre formatting, spelling, and removed the even more bizarre comment marketers around the text. Please use standard English and its existing conventions here.
• ###### 1. Re: Trouble Understanding Logic of Primes Program
Hi.

Note the condition in the inner loop. When i and j are 2 the loop is not executed. So, no "if" check is performed.
• ###### 2. Re: Trouble Understanding Logic of Primes Program
Hi. I did notice that. What I don't understand is how 2 is outputted as a prime number when the Net Beans debugger shows that i's value is 3 in the if statement. Where does the value 2 come from? Thanks.

Edited by: 996440 on Mar 27, 2013 3:07 PM
• ###### 3. Re: Trouble Understanding Logic of Primes Program
Starting at the following line use the debugger to step through the lines ONE line at a time.

for(int i = 2;....