C program to display first n prime numbers has been shown here. Here n is a positive integer. For example if n = 5, we get first 5 prime numbers i.e. 2, 3, 5, 7, 11.
Page contents:
1. C Program & output to display first N prime numbers
Code has been copied
/******************************************* alphabetacoder.com C program to display first N prime numbers ********************************************/ #include <stdio.h> #include <math.h> // function to check prime int check_prime(int num) { // declare variables int i; // 1 is not prime if (num == 1) return 0; // check divisibility of num for (i = 2; i <= sqrt(num); i++) { if (num % i == 0) { return 0; // num is composite so return false } } // num is prime so return true return 1; } int main() { // declare variables int n, num, count; // take input of the number printf("Enter the no. of primes = "); scanf("%d", & n); // initialize num = 1; count = 0; printf("First %d primes: ", n); // find n number of primes while (count < n) { // check if current number is prime if (check_prime(num)) { printf("%d ", num); count++; // increment counter } num++; // increment number } return 0; }
Output
Case 1:
Enter the no. of primes = 10
First 10 primes: 2 3 5 7 11 13 17 19 23 29
Case 2:
Enter the no. of primes = 4
First 4 primes: 2 3 5 7