This C programming example is to check whether an entered number is prime or not. A prime number is a positive integer which is divisible only by 1 and itself. For example, 3,5,7,11,17 are few prime numbers. This program check for the prime number using the modulus(%) operator.
C Program to Check if a given Number is Prime or not - Source code
Program Output
Program Explanation
1. The program accept a positive integer using the scanf function. If the number entered by the user is negative, it prompt the user to enter a positive number.
2. To check for the prime number, modulus operator is used which returns the remainder after dividing the entered number with each number up to n/2 (starting from 2).
3. If the remainder comes out zero in any case, that means the number is not prime and the variable flag is set to 1 and for loop is existed. Otherwise the value of flag remains 0.
4. Depending on the value of variable flag, message is printed on the screen using if-else statement.
need an explanation for this answer? contact us directly to get an explanation for this answer