C program to check whether a given number is prime

C program to check whether a given number is prime or not

This C program is to check whether a given number is a prime number or not.For example 5 is a prime number and 8 is not a prime number.

Logic

We are using the logic of prime number which is a prime number is divisible by 1 and number itself. So the count should be 2.If it is greater than 2 than we know that it is also divisible by another number so it then becomes a composite number.

Dry Run of the Program

Take input as integer variable ‘n’ .Let us take n=4

1st iteration   for(i=1;i<= n;i++)  i.e. for(i=1;i<=3;i++)

if (n%i==0)  i.e if(3%1==0)  this condition is true

So c is incremented  , hence c++; i.e. c=1;

2nd iteration   for(i=2;i<= n;i++)  i.e. for(i=2;i<=3;i++)

if (n%i==0)  i.e if(3%2==0)  this condition is false so c is not incremented

3rd iteration   for(i=3;i<= n;i++)  i.e. for(i=3;i<=3;i++)

if (n%i==0)  i.e if(3%3==0)  this condition is true so c is incremented

So c++; hence c=2;

For loop ends here as now when i is incremented i=4 hence i>n

Now we check the condition if(c==2)

As c=2 is true we print 3 is a prime no.

Program

#include<stdio.h> 

void main() 
{
    int n,i,c=0;
    printf("Enter any number\n");
    scanf("%d",&n);
  
    for(i=1;i<= n;i++)
    {
        if (n%i==0) 
        {
            c++;
        }
    }
    if(c==2)
    {
  	    printf("\n%d is a Prime number",n);
    }
    else 
    {
 	    printf("\n%d is not a Prime number",n);
    }
}

Output

 

Share Me!