Prime number program in C with explanation

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

What is prime number?

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

#include<stdio.h>
#include<conio.h>
void main() {
  int i = 0, n, temp = 0;
  printf("Please give input a number: ");
  scanf("%d", & n);
  for (i = 2; i <= (n / 2); i++) {
    if (n % i == 0) {
      temp = 1;
      break;
    }
  }
  if (temp == 1)
    printf("given number is not a prime number");
  else
    printf("given number is a prime number");
  getch();
}

Output 1:

Please give input a number: 23
given number is a prime number

Output 2:

Please give input a number: 44 
given number is not a prime number

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