Question: This code is to print the series of prime number up to given limit but when I am trying to execute this,it goes into infinite loop.

```
import java.io.*;
class a
{
    public static void main(String s[]) throws IOException
    {
        int count=1;
        String st;
        System.out.println("how many prime no. do you want");
        BufferedReader obj= new BufferedReader (new InputStreamReader (System.in));
        st=obj.readLine();
        int n=Integer.parseInt(st);
        while(count!=n)
        {
            int num=2;
            for(int i=2;i<num;i++)
            {
                if(num%i==0)
                {
                    count++;
                    break;
                }
            }
            num++;
        }
    }
}

```

Answer: 
Problem is value of num is always 2 at the start of loop,even if you say `num++` again it takes `num=2` which is start statement and wont enter into for loop ever,hence so infinite loop.This will Work

```
int num=2;
while(count!=n)  {         
   for(int i=2;i<num;i++) {
     if(num%i==0) {
          count++;
          break;
     }
   }
   num++;
}

```
Here is your working code:

```
import java.io.*;
    class A
    {
        public static void main(String s[]) throws IOException
        {
            int count=2;
            String st;
            System.out.println("how many prime no. do you want");
            BufferedReader obj= new BufferedReader (new InputStreamReader (System.in));
            st=obj.readLine();
            boolean isPrime = false;

            int n= Integer.parseInt(st);
            int num=3;
            if(n>=1){
                System.out.println(2);
            }
            while(count<=n)
            {
                //No need to go up to num. Up to sqrt(num) will do.
                for(int i=2;i<=Math.sqrt(num);i++)
                {
                    if(num%i==0)
                    {
                        isPrime = false;
                        break;
                    }
                }
                if(isPrime){
                    System.out.println(num);// Added the print
                    count++;
                }
                isPrime = true;
                num++;
            }
        }
    }

```