Pages

Monday, March 13, 2017

C program to check prime number

A prime number is a positive integer which is divisible only by 1 and itself. Followings are examples of prime numbers: 2, 3, 5, 7, 11, 13,17...


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

    printf("Enter a positive integer: ");
    scanf("%d",&n);
if(n <= 0)
{
printf("Enter positive number only.");
exit(0);
}
    for(i=2; i<=n/2; ++i)
    {
        //checks nonprime number
        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);
    return 0;
}


Output of program

Run-1

Enter a positive integer: 13
13 is a prime number.

Run-2

Enter a positive integer: 10
10 is not a prime number.

Run-3

Enter a positive integer: -5
Enter positive number only.


No comments:

Post a Comment