C Program to check whether the Integer given is prime or composite

For a better understanding of this C program example, we always recommend you to learn the basic topics of C programming listed below:

What are prime numbers and composite numbers?

To check whether the number given is prime or composite using a c program, we must understand the following. The prime number is an integer with no other positive divisors other than one and that number itself. Natural numbers other than the prime number are called the composite number. For example, the number '4', '6', which have more than two divisors are composite numbers. 

Let us take an example as the number '5' is a prime number because the number '5' has only two divisors: '1' and '5'. So the prime number has two divisors only.

Note:  the number '1' is not a prime number as it has only one divisor.

How to check prime number in C

Here we write a C program for finding out a number is Prime or not by using Mod Operator. First, we are checking the number is greater than 1; if not, the C program exits, displaying the number is not Prime. else we enters a 'for loop' from 1 to that number, in that loop we check "if( ( num % j ) == 0)" if it is true we prints number is not Prime. Else the given integer is prime.


STEP 1: Include the Header files to use the built-in functions in the C program.

STEP 2: Declare and Initialize the variables as an integer Data type.

STEP 3: Accept the number from the user using printf and scanf built-in functions.

STEP 4: Check the number is less than one using an 'if' condition; if so, display not a Natural number and Exit the program.

STEP 5: Open a 'for loop' from 2 to half of the number and Increment the 'j' by one. ( we have Divisors up to half of the number only]

STEP 6: Check the number Mod 'j' is zero; if so, we Assign a Flag variable as one and Break the loop.

STEP 7: Check the Flag using an 'if' condition as if the Flag is Zero, print its a Prime number else it's a Composite number.

C Source Code

                                          #include <stdio.h>
#include <stdlib.h>

void main()
        int num, j, flag;
        printf("Enter a number\n");                                 /* take the input number from user */
        scanf("%d", & num);
        if ( num <= 1)
                 printf("%d is not a prime numbers\n", num);   /* check whether number is less than 1 */
        flag = 0;
        for ( j=2; j<= num/2; j++)
               if( ( num % j ) == 0)                                 /* do the calculation using mod operator and check the given number is prime or not  */
                      flag = 1;
        if(flag == 0)
        printf("%d is a prime number\n",num);
        printf("%d is not a composite number\n", num);         /* prints the output of the program */




Enter a number
34  is not a composite number


Enter a number
29 is a prime number