C Program to Check Whether a Number is Prime or Composite

Here we have a C Program to Check whether the number entered by the user is a Prime Number or a Composite Number

A Prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself. A natural number greater than 1 that is not a prime number is called a composite number.

A Prime number has only two Factors. 1 and the number itself. But the Composite number has more than 2 factors.

The Number 1 ( One ) is neigher Prime nor Composite. Its because it has only one factor which is 1. So to become a Prime number it needs to has atleast 2 different factors and to be a Composite number it needs to have more than 2 factors.

In this program, first we ask the user to enter the number to check for prime or composite. Since the user can enter any number like 0 -ve number or 1 or greater than 1, we will check for all these conditions.

In the beginning of this program we assume that whatever the number user will enter it is a Prime Number. If the number entered by the user is greater than 1 then we will find the factors of the number other than 1 and itself.

If we find a factor other than 1 and the number itself then the number is a Composite Number else the number is a Prime number.

Prime.c

 1 #include <stdio.h>
 2 #include <stdbool.h>
 3 
 4 int main(){
 5     int number, divisor;
 6     bool isprime = true;
 7     printf("Enter the Number to check for Prime or Composite\n");
 8     scanf("%d",&number);
 9     if( number < 1 )
10         printf("Number neds to be greater than 1");
11     else if( number == 1 )
12         printf("1 is neigher Prime nor Composite");
13     else{
14         for( divisor = 2; divisor <= (number/2); divisor++ ){
15             if( ( number % divisor ) == 0 ){
16                 isprime = false;
17                 break;
18             }
19         }
20         if( isprime )
21             printf("%d is a Prime Number",number);
22         else
23             printf("%d is a Composite Number",number);
24     }
25     return 0;
26 }

Watch this video to learn how this works

is