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.
Here is the list of first 10 prime numbers:
 2
 3
 5
 7
 11
 13
 17
 19
 23
 29
Program :

#include<stdio.h>

#include<math.h>

void main()

{

int i,j,cnt,FLAG,num;

cnt = 0; // we will increase this count by 1 for each prime

LABEL:

printf(“Enter how many prime numbers do you want to prime : “);

scanf(“%d”,&num);

if(num > 0)

{

for(j=2; cnt <num ; j++)

{

FLAG=0; // set this flag to zero for each iteration

for(i=2;i <= j/2; i++)

{

if(j%i == 0)

{

FLAG = 1; // Set FLAG to 1 if given number is evenly

// divisible by any other number b/w 2 & j/2

break;

}

}

// if flag is still zero, that means Given Number is Prime.

if(FLAG == 0)

{// Number is primes, so let’s print it now.

cnt++ ; // increase count for each prime number

printf(“%d “,j);

}

}

}

else

{

printf(“Please enter positive number n“);

goto LABEL;

}

printf(“n“);

}
Output :
Related Programs:
 C Program to generate Fibonacci series upto Given Number.
 C Program to generate First N Fibonacci numbers.
 C program to Calculate Nth Fibonacci Number.
 Generating Fibonacci numbers Series using Function.
 Generating Nth Fibonacci number using Recursion.