C Program to Check Whether a Number is Prime Number or Not

prime or not in c

Check Whether a Number is Prime Number or Not.

 A number is considered as prime number when it satisfies the below conditions. 

  • Prime number is a number which can be divided by 1 and itself
  • A number which can not be divided by any other number other than 1 or itself is a prime number.
  • It should have only 2 factors. They are, 1 and the number itself.

Problem Description

In this program we will find whether a number is a prime number or not with the help of for loop or if else statement. A number is considered as prime number when it satisfies the below conditions. 

  • Prime number is a number which can be divided by 1 and itself
  • A number which can not be divided by any other number other than 1 or itself is a prime number.
  • It should have only 2 factors. They are, 1 and the number itself.

Ex- Number is 13. it have only 2 factor 

  • It is divisible by 1.
  • And it is divisible by itself

So it is a prime number.

Prime number or not in C programming

Algorithm:-

  1. Take input number n
  2.  Initialize i=1
  3.  Initialize div=0
  4.  we have to count all the divisor of number from 1 to n
  5.  run a loop from i=1 to n
    1. if n%i==0  (if n is divisible by i)
      1. increment div, div++
    2. increment i by 1 ,i++
  6. check div, if div==2 display prime, else display not prime
C++ Program to Check if a Number is Prime Number or not

C Code

#include<stdio.h>
int main()
{
    //initializing variables
    int c,number,div=0;

    //user input
    printf("Enter number: ");
    scanf("%d",&number);

    //checking for number of divisor
    for(c=1;c<=number;c++)
    {
        if(number%c==0)
       {
            div++;
       }
    }
    //no divisors other than 1 and itself
    if(div==2)
    {
        //display
        printf("%d is a prime number",number);
    }
    else
    {
         //display
         printf("%d is not a prime number",number);
    }
    return 0;
}

Output

Enter number: 2
2 is a prime number