Blog Moved

This website completely moved to new domain. For latest content, visit www.programmingposts.com

Search This Blog

7 Aug 2012

C program to Find the Number is Prime or Not

/ * C program to find the Number is Prime or not-Prime */
#include<stdio.h>
main()
{
 int n,r=1,d=2;
 printf("\n Enter the Number : ");
 scanf("%d",&n);
 if(n==2)
 {
   printf("\n %d is a Prime Number \n",n);
   exit(0); //to exit from program
 }
 r=n%d; /*we have to do this before while also becuuse
 if while condition fails then r=n%d inside while is not executed*/

 while(d<=n/2)
 {
  r=n%d;
  if(r==0)
  break; //if r==0, then to come out of while loop
  d++; //incrementing d value if(r==0) fails..
}
if(r==0||n==1) // since 1 is not a prime number
printf("\n %d is not a Prime Number \n",n);
else
printf("\n %d is a Prime Number \n",n);
return(0);
}


Output: (using GNU GCC Compiler with Code::Blocks Compiler)

No comments:

Post a Comment