A directory of Objective Type Questions covering all the Computer Science subjects. Here you can access and discuss Multiple choice questions and answers for various compitative exams and interviews.

C Program to Check if a given Number is Prime or not


Problem Description


This C programming example is to check whether an entered number is prime or not. A prime number is a positive integer which is divisible only by 1 and itself. For example, 3,5,7,11,17 are few prime numbers. This program check for the prime number using the modulus(%) operator.


C Program to Check if a given Number is Prime or not - Source code
     
                
  /* C program to check whether a given number is prime or not */

#include <stdio.h>

int main()
{
    int n, i, flag;

    printf("Enter a number \n");
    scanf("%d", &n);

    if (n <= 1)
    {
        printf("Please enter a positive number.", n);
        return 0;
    }
    flag = 0;
    for (i = 2; i <= n / 2; i++)
    {
        if ((n % i) == 0)
        {
            flag = 1;
            break;
        }
    }
    if (flag == 0)
    {
         printf("%d is a prime number \n", n);
    }

     else
     {
        printf("%d is not a prime number \n", n);
     }

     return 0;
}
     
      

Program Output


Case 1:

Enter a number
451
451 is not a prime number

Case 2:

Enter a number
79
79 is a prime number

Case 3:

Enter a number
-12
Please enter a positive number.

Program Explanation


1. The program accept a positive integer using the scanf function. If the number entered by the user is negative, it prompt the user to enter a positive number.

2. To check for the prime number, modulus operator is used which returns the remainder after dividing the entered number with each number up to n/2 (starting from 2).

3. If the remainder comes out zero in any case, that means the number is not prime and the variable flag is set to 1 and for loop is existed. Otherwise the value of flag remains 0.

4. Depending on the value of variable flag, message is printed on the screen using if-else statement.