C Program to Check Whether a Number is Prime or Not
In this example, we learn how to check whether an integer entered by the user is a prime number or not.
Remainder :
To understand this example, we should have the knowledge of the following C programming topics:
What is a prime number ?
Prime numbers are numbers that have only 2 factors: 1 and themselves. Prime numbers are divisible only by the number 1 or itself.
For example, the first 5 prime numbers are 2, 3, 5, 7, and 11.
Program to Check Prime Number
#include <stdio.h>
int main() {
int num, i, flag = 0;
printf("Enter a number : ");
scanf("%d", &num);
for (i = 1; i <= num; i++) {
if (num % i == 0) {
flag++;
}
}
if (flag == 2) {
printf("%d is a prime number", num);
}
else {
printf("%d is not a prime number", num);
}
return 0;
}
Output
Enter a number : 13
13 is a prime number
Working of the above program
- First we declare three integer variable num, i and flag and also intialize flag = 0.
int num, i, flag = 0;
printf("Enter a number : ");
scanf("%d", &num);
On each iteration it will check the if condition and if the condition is satisfied it will increment variable flag by 1. If the number is prime then it will be divided by 1 and itself i.e. it is divided by two numbers only.
for (i = 1; i <= num; i++) {
if (num % i == 0) {
flag++;
}
}
if (flag == 2) {
printf("%d is a prime number", num);
}
else {
printf("%d is not a prime number", num);
}