# C program to generate first n prime numbers

What is prime Number and C program to Check given number is Prime or Not,
Check given Number is Prime or not Using Square Root(sqrt) Function.(Efficient way),
C Program to generate prime numbers between two numbers.Now we will discuss about c program to generate first n prime numbers.

### Description :

This Program accepts one integer from the user and prints first n prime numbers. here I am using two loops one outer loop and one inner loop. Outer loop for controlling number of prime numbers and the inner loop is common prime numbers logic to check given number is prime or not.

I am also using one FLAG variable, this variable is initially 0(zero) then i am making it as 1, if number (here number means, number i got from outer loop see program for clarification) is evenly divisible by any number(other than 1 and itself).

This program has one more key variable that is cnt variable. this will control the number of prime numbers and outer loop. this variable also initially zero and I am increasing it by 1 for each prime number.

1. 2
1. 3
1. 5
1. 7
1. 11
1. 13
1. 17
1. 19
1. 23
1. 29

### Program :

1. #include<stdio.h>
2. #include<math.h>
3. void main()
4. {
5.     int i,j,cnt,FLAG,num;
6.     cnt = 0;  // we will increase this count by 1 for each prime
7. LABEL:
8.     printf(“Enter how many prime numbers do you want to prime : “);
9.     scanf(“%d”,&num);
10.     if(num > 0)
11.     {
12.         for(j=2; cnt <num ; j++)
13.         {
14.             FLAG=0;  // set this flag to zero for each iteration
15.             for(i=2;<= j/2; i++)
16.             {
17.                 if(j%== 0)
18.                 {
19.                     FLAG = 1;  // Set FLAG to 1 if given number is evenly
20.                                // divisible by any other number b/w 2 & j/2
21.                     break;
22.                 }
23.             }
24.             // if flag is still zero, that means Given Number is Prime.
25.             if(FLAG == 0)
26.             {// Number is primes, so let’s print it now.
27.                 cnt++ ;     // increase count for each prime number
28.                 printf(“%d “,j);
29.             }
30.         }
31.     }
32.     else
33.     {
34.         printf(“Please enter positive number n);
35.         goto LABEL;
36.     }
37.     printf(n);
38. }

### Related Programs:

Venkat

Hi Guys, I am Venkatesh. I am a programmer and an Open Source enthusiast. I write about programming and technology on this blog.