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

C Program to Check Whether a Number is Prime or Not

In this example, we learn how to check whether an integer entered by the user is a prime number or not.

Remainder :

To understand this example, we should have the knowledge of the following C programming topics:



What is a prime number ?

Prime numbers are numbers that have only 2 factors: 1 and themselves. Prime numbers are divisible only by the number 1 or itself.
For example, the first 5 prime numbers are 2, 3, 5, 7, and 11.


Program to Check Prime Number

#include <stdio.h>

int main() {
  int num, i, flag = 0;
  printf("Enter a number : ");
  scanf("%d", &num);
  for (i = 1; i <= num; i++) {
    if (num % i == 0) {
    flag++;
    }
  }
  if (flag == 2) {
    printf("%d is a prime number", num);
  }
  else {
    printf("%d is not a prime number", num);
  }
  return 0;
}

Output

Enter a number : 13
13 is a prime number

Working of the above program

  • First we declare three integer variable num, i and flag and also intialize flag = 0.
  • int num, i, flag = 0;
  • Then we asked the user to enter an integer.
  • printf("Enter a number : ");
  • Then we take the user input using scanf() function and store the entered value in num variable.
  • scanf("%d", &num);
  • Then we use a for loop in which we initialize i = 1 and increment at every iteration to run loop until i <= num. And in the for loop we put a if statement to check num % i == 0 i.e. on dividing num by i we get 0 as remainder or not (completely divisible or not).
    On each iteration it will check the if condition and if the condition is satisfied it will increment variable flag by 1. If the number is prime then it will be divided by 1 and itself i.e. it is divided by two numbers only.
  • for (i = 1; i <= num; i++) {
      if (num % i == 0) {
      flag++;
      }
    }
  • Finally, we use the if...else statement and check that the value of flag is equal to 2 or not. If flag == 2 than it is a prime number i.e. only divisible by 1 or itself.
  •   if (flag == 2) {
        printf("%d is a prime number", num);
      }
      else {
        printf("%d is not a prime number", num);
      }

- Related Topics