Home C Language Basic C Programs Print ‘n’ Prime numbers in C

Print ‘n’ Prime numbers in C

## Write a C program to generate first ‘n’ prime numbers, where n is a value Supplied by the user.

#include<stdio.h>

int main()

{

int a,i,x=1,count,c=0;

printf(“Enter a number :”);

scanf(“%d”,&a); //Read number of primes required

printf(“The first %d primes are :\n”,a);

while(c<a)

{

count=0; //set count as zero to count factors of current number (x).

for(i=1;i<=x;i++)

{

if(x%i==0) //check the iteration value is factor of current number or not.

count++;

}

if(count==2) //Every prime number should have only two factors.

{

printf(“%d\t”,x);

c++;

}

x++;

}

return c;

}

Output :

Enter a number : 30

The first 30 primes are :

2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 71 73 79 83 89 97 101 103 107 109 113

For improvement of your coding skills we give some tasks along this. If you solve this tasks and send to our email (onlineexamshubteam@gmail.com) with your details. We will display your details (like Name, City, college, photo) in our site.

Task : Write a c program to print all primes from first ‘n’ natural number.