Thursday, 19 September 2013

Program to ckeck for a prime

// Program to ckeck for a prime

 

#include<stdio.h>  //Preprocessor statement

#include<conio.h>  //Preprocessor statement

void main()             //main function begins

{

  int n,i;                 // integer variable declaration

  char flag=’f’;      //character variable declaration

  clrscr();             //to clear the output screen

  printf(“ enter an integer value “); // display the message

  scanf(“%d”,&n); // read the value from keyboard and  

                      //store in the address location of variable n

                      // check for prime logic begins

  if(n<=0)

   {

         printf(“\n undefined”);

       }

  else if(n==1)

       {

       printf(“\n Natural Number”);

       }

  else if((n==2)||(n==3)) 

       {

         printf(“\n The Number is Prime”);

       }

  else          // this else part is for numbers > 3

       {        // remainder after division is checked taking                 

                //divisors from 2 to n/2 values if for any value              

               //the remainder is zero flag is changed to ‘t’ so

              //that further checking is stopped

          i=2;

       while((i<=n/2)&&(flag==’f’))

              {

                if((n%i)==0)

                     {

                           flag=’t’;

                     }

               i++;

              }                   // end of while loop

         if(flag==’t’)

              {

                     printf(“\n The number is not Prime”);

              }

         else

              {

                     printf(“\n The number is Prime”);

              }

        }                // end of else for numbers > 3

 

  getch();

}

No comments:

Post a Comment