Write a program in C to check whether a Number is Prime Number or not

Prime Number :

Before writing program we have to understand what is a Prime Number. A Prime Number is a natural which is divisible by 1 and itself and can not be divisible by any other number. In other words a natural number greater than 1 and has no positive divisor except 1 and itself. For example – 2, 3, 5, 7, 11, 13, 17 etc.

The idea is to iterate through all numbers from i=2 to i<= n-1 using for loop and for every number check if it divides n . To solve the problem, logic here is every natural numbers greater than 1 is divisible by 1. So we will start the for loop from i=2 and ends at i<=n-1. As we know Prime Number is divisible by 1 and itself only.

If( i<=n-1) false and for loop terminate i.e. we did not find any number between i=2 to i<=n-1 which divides n. It indicate number is Prime Number. If (n%i==0) true i.e. we find any numbers that divides n. Then for loop will terminate. It indicate number is not prime.

Lastly if (i==n) that means it iterated all the steps until i<=n-1 is false i.e. state of prime number.

int main()
   int n,i;
   // Ask user to input a number
   printf("Enter a Number:");
   // store user input to variable n
   scanf("%d", &n);
   //iterate from 2 to n-1
   for(i=2; i<=n-1; i++)
       // if n is divisible by any number between 2 and n-1 , it is not 
          prime number
      if(n%i == 0)
      printf("%d is a Prime Number", n);
       printf(" %d is not a Prime Number", n);


Share This!

Leave a Reply

Your email address will not be published.