Search code examples
javawhile-loop

Printing prime numbers using while loop, not working as desired


The inner while loop variable j remains at 3 after incrementating, instead it should be 1 for next iteration. Due to this, the inner while condition fails and gets terminated and output is only 2, instead of 2, 3, 5.

public static void main(String[] args) {

    int i=2;
    int j=1;
    int count=0;

    while(i<=5)
    {
        while(j<=i)
        {
            if(i%j==0)
            {
                count++;        
            }
            
            j++;
        }

        if(count==2)
            System.out.println(i);    
        
        i++;
    }

Solution

  • You need to reset the inner loop variable j and the count for each execution of the outer loop:

    public static void main(String[] args) {
    
        int i = 2;
    
        while (i <= 5) {
            int j = 1;
            int count = 0;
    
            while (j <= i) {
                if (i % j == 0) {
                    count++;
                }
                j++;
            }
    
            if (count == 2) {
                System.out.println(i);
            }
            i++;
        }
    }