Check Prime number in C
Here, you will get and learn the program code to Check Prime Number in C Programming language using 3 different ways.
Prime Number
A prime number is a positive number that has only two divisor,1 and itself. The following numbers are prime number because they have only two divisors.
2, 3, 5, 7, 11, 13, 17, 23,29…..
Different 3 Ways to Check Prime Number in C
Here we will tell you to create prime number check program by using 3 different kinds of methods.
Prime Number Check using for loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | //Prime check using for loop #include <stdio.h> int main() { int n, i, flag = 0; printf("Enter an integer Number : "); scanf("%d", &n); for (i = 2; i <= n/2; ++i) { if (n % i == 0) { flag = 1; break; } } if (flag == 0) printf("%d is a prime number.", n); else printf("%d is not a prime number.", n); return 0; } |
Output
Prime Number Check using functions
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | //Prime check using functions #include <stdio.h> int is_prime(int num) { int i; for(i = 2; i <= num/2; i++) { if (num % i == 0) { return 0; } } return 1; } int main() { int n, result; printf("Enter an integer Number: "); scanf("%d", &n); result = is_prime(n); if (result == 1) printf("%d is a prime number.", n); else printf("%d is not a prime number.", n); return 0; } |
Output
Prime Number Check using Recursion
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | //Prime check using recursion in C #include <stdio.h> //Recursive Function int prime(int num, int i) { if (i == 1) return 1; else { if (num % i == 0) return 0; else return prime(num, i - 1); } } int main() { int num, check; printf("Enter a number: "); scanf("%d", &num); check = prime(num, num / 2); if (check == 1) printf("%d is a Prime numbern", num); else printf("%d is not a Prime numbern", num); return 0; } |
Output
Check out our other C programming Examples