Check if given Number is Prime Number Program in C Language
To check if given number is prime number or not in C programming, check if there is any factor greater than 2. If any factor is found, then the given number is not prime. If there is no factor at all, then the given number is prime number.
C Program
In the following program, we read a number to n from user via console input, and check if there is any factor to decide whether the given number is prime number or not. We use C For Loop to iterate over the possible factors.
main.c
</>
Copy
#include <stdio.h>
#include <stdbool.h>
int main() {
int n;
printf("Enter a number : ");
scanf("%d", &n);
bool isPrime = true;
if (n == 0 || n == 1) {
isPrime = false;
}
else {
int i = 0;
for (i = 2; i <= n / 2; ++i) {
if (n % i == 0) {
isPrime = false;
break;
}
}
}
if (isPrime) {
printf("%d is a Prime Number.\n", n);
} else {
printf("%d is not a Prime Number.\n", n);
}
}
Output
Enter a number : 7
7 is a Prime Number.
Program ended with exit code: 0
Output
Enter a number : 12
12 is not a Prime Number.
Program ended with exit code: 0
Conclusion
In this C Tutorial, we learned how to check if given number is prime number or not in C programming, with examples.