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++;
}

```
```
import java.util.*;
class Prime
{
  public static void main(String[] args) {
  Scanner sc = new Scanner(System.in);

    System.out.println("enter  the  no of prime nos want:  ");
    int n2 = sc.nextInt();
    int flag = 1 ;
    int count = 0 ;
    for (int i =2; i<99999;i++ )
    {
         for (int j=2; j<i;j++ )
         {
          if (i%j == 0)
          {
             flag = 0;
             break;
          }
          else
          {
            flag =1;
          }
         }

      if (flag == 1)
      {
          System.out.print(i +"\t");
          count++ ;
      }
      if (count == n2)
      {
          break  ;
      }
    }
  }
}

```