C Program To Determine Whether Or Not A Number Is Prime

This tutorial will teach you how to write a C program to determine whether a number is prime or not.
If a positive number is divisible by 1 and itself, it is called a prime number. For example, the numbers 13, 19, and 23 are prime because they are divisible by one and themselves.

A program that determines whether a number is prime or not

In this example, we are determining whether or not the number entered by the user is a prime number.
The first check is to compare the input number to 0 and 1; if it is either 0 or 1, it is not a prime number.
The second check we perform here is to see if the input number is divisible by any number between 2 and num/2; if it is, it is not a prime number; otherwise, it is.

#include <stdio.h>

int main() {

  //Here flag value 0 means prime number and
  //1 means non-prime number
  int num, i, flag = 0;
  printf("Enter a number to check whether prime or not: ");
  scanf("%d", &num);

  // 0 and 1 are not the prime numbers so setting
  // the flag to 1 if entered number is 0 or 1
  if (num == 0 || num == 1)
  flag = 1;

  for (i = 2; i <= num / 2; ++i) {

    // if num is divisible by i, then num is not prime
    // change the flag value to 1
    if (num % i == 0) {
      flag = 1;

  // If flag is 0 it means the number is prime
  if (flag == 0)
    printf("Entered number %d is a prime number.", num);
    printf("Entered number %d is not a prime number.", num);

  return 0;

Output: Because the user entered the number 13, which is a prime number, the program displays the message “Entered number 13 is a prime number.”

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button