C Program to Check if a Number is Prime or Not


The program to check prime number is written using Dev-C++ compiler installed on a Windows 7 64-bit system. You can use any other standard compiler to compile the program and it will still work.This program is intended for beginners learning C programming language. To help you understand the program, you will find following section helpful – problem definition, flowchart, program code and verified output.

Problem Definition

Prime numbers are very important topic in mathematics. It is usually easy to find the small prime numbers, but very difficult to identify a prime number, when the numbers grow larger.We want to write a program to test whether a given number is a prime number or not.

What is a Prime number ?

Any positive number greater than 1 which is divisible only by itself and number one is called a Prime number, all other numbers are Composite numbers.

For example

63 = 3 x 21 

The number 63 has two factors 2 and 21, therefore it is a composite number.

73 = 73 x 1 

The factors of number 73 are 73 itself and 1, therefore, 73 is a prime number.

How do we process the given input number?

Here are the steps to process the input number in the program.

Step 1 – Get the number, N

Step 2 – Check if the number, N is divisible by 2,3, or 5

Step 3 – If the number, N is divisible, then the remainder = = 0

Step 4 – If number is divisible, then check = 0, check = 1

Step 5 – If check = = 1, number is a prime number

Step 6 – Print the output

Step 7 – End the program

Flowchart – Program to check a Prime number

Flowchart- C Program to Check Prime Number
Flowchart- Program to Check Prime Number

Program Code 

/*Program to Check if the number is Prime or not */
#include <stdio.h>
#include <conio.h>
main()
{ int i,check,num; int a,b,c; /* Get the number */
printf("Enter a number:");
scanf("%d",&num);
/* check if the number is divisible by 2,3 or 5*/
for( i=1; i<=5;i++)
{
if(num % i == 0)
{
check = 0;
}
else
{
check = 1;
}
}
/*print the result */
if(check == 1)
{
for(i=0;i<35;i++)
printf("_");printf("\n\n");
printf("The Number %d is a Prime Number\n\n",num);
for(i=0;i<35;i++)
printf("_");printf("\n\n");
}
else
{
for(i=0;i<35;i++)
printf("_");printf("\n\n");
printf("The Number %d is not a Prime Number\n\n",num);
for(i=0;i<35;i++)
printf("_");printf("\n\n");
}
getch();
return 0;
}

 

 

Output

The output of the above program is given below.

Output-Prime Number Check in C Programming
Output-Prime Number Check