C Program to Check Whether given Number is Prime or Not | detect prime number or not in c Language

Program Description :

Write a Program to check whether a number is a prime number or not in C Language. The program should accept one Integer from the user and checks if it is prime or not.

What is Prime Number :

  • A Prime Number can be divided evenly only by 1, or itself.
  • A Prime Number must be a whole number greater than 1.

Example:

  • 3 can only be divided evenly by 1 or 3, so it is a prime number.
  • But 6 can be divided evenly by 1, 2, 3 and 6 so it is NOT a prime number.

Note : There are other efficient ways to write this program. we will discuss them in next posts.

Program to check number is Prime number or not in C Language :

We will use one flag variable and set that flag to 1 if the given number is evenly dividable by any number (except 1 and the given number). That’s why my for loop is started with 2 and ended at n/2

  1. #include<stdio.h>
  2. void main()
  3. {
  4.         int FLAG,i,num;
  5.         // first set the flag to 0
  6.         FLAG = 0;
  7.         printf(“Enter any positive Number : “);
  8.         scanf(“%d”,&num);
  9.         for(i=2;i<num/2 ; i++)
  10.         {
  11.                 if(num%== 0)
  12.                 {
  13.                         FLAG=1;
  14.                         break;
  15.                 }
  16.         }      
  17.         // check if FLAG is 0 or 1
  18.         // if FLAG is 0 then Number is Prime.
  19.         // otherwise Number is not Prime.
  20.         if(FLAG == 0)
  21.                 printf(“%d is Prime Number  \n,num);
  22.         else
  23.                 printf(“%d is not a prime Number \n,num);
  24. }

Venkatesh

Hi Guys, I am Venkatesh. I am a programmer and an Open Source enthusiast. I write about programming and technology on this blog.

You may also like...

7 Responses

  1. […] What is Prime Number and C program to Check given number is Prime or Not […]

  2. […] What is Prime Number and C program to Check given number is Prime or Not […]

  3. […] What is Prime Number and C program to Check given number is Prime or Not […]

  4. […] C Program to Check number is Prime Number or not? […]

  5. […] C Program to Check number is Prime Number or not? […]

  6. […] C Program to Check number is Prime Number or not? […]

  7. […] C Program to Check number is Prime Number or not? […]

Leave a Reply