C Program to Check Whether a Number is Prime or Not
C program to check whether entered number is prime or not, C program will take user input and will test entered number is prime or not .
What is prime number in C program ?
Prime Number are natural numbers ( 1 2 3 4 5 …………………), a number completely divisible by exactly 2 natural numbers by 1 or number itself is a prime number .
if you take 1 to check whether prime number or not.
Solution
1 is completely divisible only itself but not divisible any other numbers, by definition a number completely divisible by exactly 2 natural numbers so 1 is not prime number
if you take 2 to check whether prime number or not.
2 is completely divisible by 1 and divisible itself, by definition a number completely divisible by exactly 2 natural numbers so 2 is prime number ‘
if you take 4 to check whether prime number or not.
4 is completely divisible by 1,2 and 4 itself so this is prime number.
C program to check prime number
#include <stdio.h>
int main()
{
int num, i, flag=0;
printf(“Please Enter a Number “);
scanf(“%d”, &num);
for(i=2; i<=num/2; i++)
{
if(num%i==0)
{
flag=1;
break;
}
}
if(flag==0)
printf(” You have Entered %d Which is A Prime Number “, num);
else
printf(” You have Entered %d Which is not a prime number”, num);
return 0;
}
Run this program and Enter any number
if user enter is 5
Output
You have entered 5Which is A Prime Number
C program to check prime number in C programing Language
C program to check prime number in C
Note –
For Loop will start form 2 and i<=num/2 this part will run till half value to give number by user and given number will divided by two.
if(num%i==0) Modulus Operator check reminder of given number by user, if reminder is 0 (zero) that mean not prime number
if flag set on zero, line no 18 if part will be executed other else statement will printed .