PRIME or COMPOSITE

 Write a C program to check whether a number is prime or composite .

#include<stdio.h>
int main()
{
    int i,n,c=0;
    printf ("Enter a number n");
    scanf ("%d",&n);
    for (i=1;i<=n;i++)
    {
        if(n%i==0)
        c=c+1;
    }
    if (c==2)
    printf ("The number is PRIME");
    else
    printf ("The number is COMPOSITE");
    return 0;
}

Here, the number entered by the user is stored in variable n. The loop goes on from 1 to the number itself and inside the loop, the number is divided by i (i starts from 1 and increases by 1 in each loop). If the number is exactly divisible by i then the value of c is incremented by 1. Then, if the value of c is 2, it means that the number is divisible by only 2 numbers (i.e. 1 and the number itself) so the entered number is a prime number. Otherwise, it is a composite number.

Output:

5

=>The number is PRIME.

8

=>The number is COMPOSITE.


Post a Comment

0 Comments