Prime Number Program in C
On this page (8sections)
About this program
This is an example program in c other programs. Read the concept first: If Else Statement in C, then study the code and output below.
Introduction
A prime number is a natural number greater than 1 that has no divisors other than 1 and itself. Checking primality is a classic C exercise that combines loops, conditionals and the modulo operator.
Algorithm
- If
n <= 1, it is not prime. - Test divisibility from 2 to
n/2(or up tosqrt(n)for efficiency). - If any number divides
nevenly,nis not prime. - Otherwise,
nis prime.
Prime Number Check Program
#include <stdio.h>
int main(void) {
int n, i, isPrime = 1;
printf("Enter a positive integer: ");
scanf("%d", &n);
if (n <= 1) {
isPrime = 0;
} else {
for (i = 2; i <= n / 2; i++) {
if (n % i == 0) {
isPrime = 0;
break;
}
}
}
if (isPrime)
printf("%d is a prime number\n", n);
else
printf("%d is not a prime number\n", n);
return 0;
}
Sample Output
Enter a positive integer: 17
17 is a prime number
Enter a positive integer: 20
20 is not a prime number
Print Primes from 1 to N
#include <stdio.h>
int main(void) {
int n, num, i, count = 0;
printf("Enter upper limit: ");
scanf("%d", &n);
printf("Prime numbers up to %d:\n", n);
for (num = 2; num <= n; num++) {
for (i = 2; i <= num / 2; i++)
if (num % i == 0) break;
if (i > num / 2) {
printf("%d ", num);
count++;
}
}
printf("\nTotal: %d primes\n", count);
return 0;
}
Sample Output
Enter upper limit: 30
Prime numbers up to 30:
2 3 5 7 11 13 17 19 23 29
Total: 10 primes
Related Programs
See also Odd Or Even and Print 1 to N.