Prime number program in C with explanation

prime number program in c

In this tutorial we are going to learn how to write a program to check whether a given integer number by user is a prime number or not in C programming language.


If given number is prime then our logic will assign value 0 to a temp variable and will print “number is prime” and if the number is not prime then our logic will assign value 1 to a temp variable program will print “number is not prime”.


Before directly moving on the writing prime number program in c, first you should know

In Mathematical term, A prime number is a number which can be divided by only 1 and number itself.

For example : 2, 3, 5, 7, 13,…

Here 2, 3 or any of the above number can only be divided by 1 or number itself.

How our program will behave?

Suppose if someone gives an input 2 then our program should give output “given number is a prime number”.

And if someone gives 4 as  an input then our program should give output “given number is not a prime number”.

C program to check given number is prime or not

void main(){
int i=0,n,temp=0;
	printf("Please give input a number: ");
		printf("given number is not a prime number");
		printf("given number is a prime number");


C Program to check a given number is Prime number or not

Explanation of Prime number program in c

  • In the above program I have taken 3 variables of integer type.
  • Variables are i, n  and temp. variables i and temp has initialized with value 0 and n will store user given input integer.
  • Now our main logic starts from the for loop.
  • We have tried to iterate the for loop upto half time of the given integer input by the user.
  • If the input number is divisible by any number which is less than the half of the input number, it means that there is a number exit instead of 1 which divides the number.
  • Means given number is not a prime. If not a prime then the value of temp variable will changed and new assigned value is 1.
  • Now if temp has value 1 then if condition will satisfy and execute.
  • And it will print “given number is not a prime number”.

I hope this is now clear to you.

Leave a Comment