C Program to Check Prime Number

In this program we will check if a number entered by the user is prime or not. A prime number is a number which can be divided only by 1 and itself. For example 7, 13, 17, 23 and so on.

To understand this program, you must know the following topics in C

  • Conditional statements
  • Loops
  • Break and continue statement

Program

#include<stdio.h>
int main()
{
    int i, number, check=0;
    printf("Enter the number");
    scanf("%d", &number);
    for(i = 2; i < number; i++)
    {
        if(number % i == 0)
        {
            check++;
            break;
        }
    }
    if(check == 0)
    {
        printf("The number is prime");
    }
    else
    {
        printf("The number is not prime");
    }
return 0;
}

Output:
1
Enter a positive number15
The number is not prime

2
Enter a positive number17
The number is prime

Explanation:

  • First we have included the standard library ‘stdio’ so as we could use the inbuilt functions ‘printf’ and ‘scanf’. Then, we have declared three variables – number, i, and check and initialized the variable check with 0. We are using the variable number to store the number entered by the user, the variable ‘i’ would be used to run the loop and variable ‘check’ would be used to decide which message to display.
  • Then we are asking the user to enter a positive number by displaying a message with the printf() function. The number would get stored in the number variable using the scanf() function.
  • Next we have started a for loop that will run from 2 to the number that the user will enter. For example if the user enter 10, the loop will run from 2 to 10. Every time the loop runs, we are checking if the number is completely divisible by the current value of i or not. If it is divisible by any number in this range (2 – number), we can say the number is not prime. In this case the value of check is incremented and the loop will break.
  • When the loop terminate, we can check for the value of the variable named ‘check’. If its value is still 0, that means the condition inside the loop never became true, and the number is prime and if the value of check has incremented then the number is not prime.
  • So lastly we have put if and else statements. If the value of check is equal to zero, the program will end up by displaying a message that says “The number is prime”, else the message “The number is not prime” will be displayed.

Code written using while loop

#include<stdio.h>
int main()
{
    int i = 2, number, check = 0;
    printf("Enter the number");
    scanf("%d", &number);
    while(i < number)
    {
        if(number % i == 0)
        {
            check++;
            break;
        }
        i++;
    }
    if(check == 0)
    {
        printf("The number is prime");
    }
    else
    {
        printf("The number is not prime");
    }
    return 0;
}