C Program to Check a number is a Prime number or not.

C Program to check prime number is one of the most important questions form the placement point of view.
If you will go for an interview in any IT company, there are very chances that you will get this question. So, if you do not the solution to this problem, Shout Coders have come with the solution.
If you are a beginner and do not know anything about the C Programming language. Please Read Introduction to C language and Structure of C program. After this, you will be able to understand the program easily.
What is Prime Number-
Prime Number is a special type of number which is only divisible by one and the number itself. Any number following the above conditions is a prime number.
Example of Prime Number –
19 is a prime number as it is only divisible by 1 and 19. Some of the Prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 and the list goes on.
Method 1 – C Program to Check Prime Number –
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 |
#include <stdio.h> int main() { int n, i, flag = 0; printf("Enter a positive integer: "); scanf("%d", &n); for (i = 2; i <= n / 2; ++i) { // condition for non-prime if (n % i == 0) { flag = 1; break; } } if (n == 1) { printf("1 is neither prime nor composite."); } else { if (flag == 0) printf("%d is a prime number.", n); else printf("%d is not a prime number.", n); } return 0; } |
Output – Enter a positive integer: 3 3 is a prime number.
Try to make a function, which will take a number from the user and will return the answer.
For running the program online, please check this online Integrated Development Environment (IDE). Online Compiler.
Frequently Asked Questions (FAQ)
Yes, you can check the Sieve of Eratosthenes, it is very fast.
Yes, many major companies ask this question.
No, 0 is not a prime number.
No, yes is not a platform-independent language.