C program to check whether a number is prime or not

In this article, you will learn about c program to check prime number.

What is prime number ?

A prime number is a natural number that is divisible by 1 and itself only.

For example 2, 3, 5, 7….

Please go through following articles of C programming to understand the logic of the program.

C program to check prime number

#include <stdio.h>

int main()
{
   int num, i, j = 0;

   printf("Enter number: ");
   scanf("%d", &num);

   //check for prime number
   for (i = 1; i <= num; i++)
   {
      if ((num % i) == 0)
         {
            j++;
         }
   }

   if (j == 2)
      printf("%d is a prime number.", num);
   else
      printf("%d is not a prime number.", num);

   return 0;
}

[adsense1]
Output
c program to check prime number

Explanation

Program logic of the above program to check whether a number is prime or not is simple. We know that prime number is only divisible by 1 and itself.

Hence every time the program flow enters for loop it checks whether the number is divisible by iteration number.

If the given number is perfectly divided by iteration number then j is increased by 1. This continues till iteration reached to number itself.

Finally, the value of j is checked and if it is equal to 2, the result is a prime number.