Vaibhav Agarwal
Vaibhav Agarwal

Reputation: 975

Initialization of boolean variable while using "for" loop in Java

I have an interesting question. I am writing a program to print prime numbers between 1 and 100. First let me show you my code:

public class Lessons {
    public static void main(String[] args) {
        int b;
        boolean isPrime = true;

        for (int a=2; a<=100; a++) {
            for (b=2; b<a;b++) {
                if (a%b==0) {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime) {
                 System.out.println(a);
            }
        }
    }
}

The output of this program is 2 3 which is wrong. However, if I initialize Boolean variable boolean isPrime = true; inside the first for loop, I get correct list of prime numbers. Can anyone help me understand why position of Boolean variable initialization is affecting the output??

Upvotes: 0

Views: 2719

Answers (4)

Sergio S
Sergio S

Reputation: 41

As you have initialized you boolena var outside the outer loop once in the inner loop it is set to false, in the next it del outer loop no matter if the number is prime or not it wont be printes cause the var its still false, thats because you need to re-initialized the var every time an outer loop begins, thats to put it into the outer loop (as you said the first for loop)

I hope it will be helpfull, forgive my english i am not a native speaker!

Upvotes: 0

Gee Bee
Gee Bee

Reputation: 1794

It is easy. Your logic works so that you assume that the number is a prime number unless you find that it has a divisor in the inner loop (so it is not a prime).

The problem is that once you found a non-prime number (e.g. 4) the boolean remains false forever, and no other prime numbers are getting printed.

Therefore, you have to reset the boolean to true inside the outer for loop as you tried. This ensures that checking of each prime candidates works on the same logic:

  • first we assume that the candidate is a prime number
  • unless we proove in the inner for loop that it is not

Upvotes: 0

Zolt&#225;n
Zolt&#225;n

Reputation: 22156

The reason is that once you find one non-prime number, your isPrime variable is set to false, and it remains false for all other values of the variable a. As you've correctly discovered, you need to reset isPrime to true for each new a value, i.e. initialize it inside the outer loop.

Upvotes: 1

Erick G. Hagstrom
Erick G. Hagstrom

Reputation: 4945

You need to think about what that variable means. I think it probably means "is the current value of a prime?". Then, every time a takes a new value you need to start over, and--given your approach--treat it as prime until you prove that it isn't.

If you initialize it before the first for loop, you're really asking "are all values of a that I've seen so far prime?". Clearly that is true for 2 and 3, but as soon as you evaluate 4 it gets set to false and stays there forever.

This isn't really related to where the variable is initialized per se. You could leave it where it is, as long as you assign it a value of true before entering the inner for loop. The important point is that each value of a gets a chance to be evaluated on its own merits without carrying over results from previous values.

So this would work:

public static void main(String[] args) {
    int b;
    boolean isPrime;

    for (int a=2; a<=100; a++)
    {
        isPrime = true;
        for (b=2; b<a;b++)
        {
            if (a%b==0)    
            {
                isPrime = false;
                break;
            }
        }
        if (isPrime)
        {
            System.out.println(a);
        }
    }
}

Upvotes: 1

Related Questions