Monday 5 December 2016

Simple C Program to Check Whether given Number is Prime or Not

     
   
   Prime Number - defn
        
                 Prime Number can be divided evenly only by 1, or itself. And it must be a whole number greater than 1. 

  •  Most of the new c language beginers didnt know to code for checking prime number or not
  • Here this blog tell the logic of prime number check


C-Code

#include <stdio.h>
main()
{
    int n, i, flag = 0;

    printf("Enter a positive integer: ");
    scanf("%d",&n);

    for(i=2; i<=n/2; i++)
    {
        if(n%i==0)
        {
            flag=1;
            break;
        }
    }

    if (flag==0)
        printf("%d is a prime number.",n);
    else
        printf("%d is not a prime number.",n);
    
}

  1. %   it will return  number that the  remainder of the division ( / it will return quotient of division)
  2. (flag) is a simple variable that keeps on checking the state of any operation at any iteration.
  3. using modulus operator ,get the remainder if the remainder is not equal to 0 
  4. then the flag is set to 0 ,at end of for loop flag  value is 0.
  5. then display the message as prime number.
this is a simple logic for prime number checking,if u have further doubts commend me

No comments:

Post a Comment