C Program to Check Whether a Number is Prime or Composite

A prime number is the number which can be exactly divided by only 1 and the number itself. For example, 11 can only be exactly divided by 1 and the number itself, so 11 is a prime number. But 14 can be divided by 1, 2, 7 and 14 so it is not a prime number but a composite number.

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

#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:

Enter a number

5

The number is PRIME

Enter a number

10

The number is COMPOSITE