C Program to Check a Number is Prime or Not | C Programming Examples
C Programming Examples:
1. Write a C Program to Print a Number is Prime or Not
2. C program to Check a Number is Prime or Not
3. How to Find a Number is Prime or Not
#include<stdio.h>
int main()
{
int num,i,count=0;
printf("Enter a number to check whether it is prime or not\n");
scanf("%d",&num);
for(i=1;i<=num;i++)
{
if(num%i==0)
{
count++;
}
}
if(count==2)
{
printf("The given number %d is Prime Number\n",num);
}
else
{
printf("The given number %d is not Prime Number\n because The number is divisible by\n",num);
for(i=1;i<=num;i++)
{
if(num%i==0)
{
printf("%d\n",i);
}
}
}
}
Explanation of Finding a Number is Prime or Not in C Programming :
The prime number should be divisible by 1 and itself. This is the main concept of this program.
The program starts with initializing
num → To store number
i → Temporary variable
count → To store number of divisors
printf("Enter a number to check whether it is prime or not\n");
scanf("%d",&num);
To take number from user
for(i=1;i<=num;i++)
{
if(num%i==0)
{
count++;
}
}
Let us assume num=253. The loop will traverse from i=1 to 253. In each iteration the number num=253 is divided by i. For example,
Iteration 1:i=1,i less than 253
In if num%i==0 → 253%1==0 which is true
Then count increments by 1.So count=1;
Iteration 2:i=2,i less than 253
In if num%i==0 → 253%2==0 which is false
As the condition is false the count remains same so count is still count=1
Iteration 3:i=3,i less than 253
In if num%i==0 → 253%3==0 which is false
As the condition is false the count remains same so count is still count=1
Like this it goes on till iteration 11
Iteration 11: i=11,i less than 253
In if num%i==0 → 253%11==0 which is true
Then count increments by 1.So count=2;
Like this for every divisor of number(253) the count will get incremented and in this case of number(253) there are 4 divisors (they are:1,11,13,153) until i=253
So the count=4
if(count==2)
{
printf("The given number %d is Prime Number\n",num)
}
else
{
printf("The given number %d is not Prime Number\n
because The number is divisible by\n",num);
for(i=1;i<=num;i++)
{
if(num%i==0)
{
printf("%d\n",i);
}
}
}
As for Prime number there will be only 2 divisors 1 and the number itself If the number is prime number the count will be 2(i.e. count=2) But in this case where number is 253 the count=4 so the condition will be false and prints that it is not a prime number and display its divisors using the same logic as in case of counting number of divisors except instead of using count to increment we used printf to print values of divisors.
0 Response to C Program to Check a Number is Prime or Not | C Programming Examples
Post a Comment