C Program to Check if a Number is Prime or Composite

General Introduction:

Prime Numbers: Prime Numbers are those numbers which are only divisible by 1 and itself. Example: 2,3,5,7,11…
Composite Numbers: Composite Numbers are those numbers which are divisible by more than 2 numbers. Example: 4,6,8,9,10….

The logic behind the code below:

a) The entered number is processed in a loop from 1 to n/2.
b) In each loop (number%i==0) condition is checked to know if the entered number is exactly divisible by i(the number in the loop which keeps on increasing).
c) If the number is exactly divisible by i i.e (number%i==0), then the flag is increased by 1.
d) At the end, if the value of the flag is 1, i.e the number is divisible by 1 only, therefore, print that the number is a prime number.
e) If the value of flag is other than 1, the number is divisible by that many numbers till number/2 condition. Therefore print the number is a composite number.

Code in C:

/* C Program to check if a number is prime or composite */
#include<stdio.h>
#include<conio.h>
int main()
{
	int number; /*to store the number */
	int i; /*to control the loop */
	int flag; /*to know how many numbers exactly divides the entered number*/
	flag=0;
	
	printf("Enter a number to check if the prime or composite: ");
	scanf("%d",&number);
	
	for(i=1;i<=number/2;i++)
	{
		if(number%i==0)
		{
			flag++;
		}
	}
	
	if(number==1)
	{
		printf("\n1 is neither prime nor composite");
	}
	
	else
	{
		if(flag==1)
		{
			printf("\nThe number %d is prime",number);
		}
		
		else
		{
			printf("\nThe number %d is composite as it is divisible by %d numbers",number,flag+1);
		}
	}
	
	getch();
	return(0);
}

Outputs:

C Program to Check if a Number is Prime or Composite
Output when the entered number is 1
C Program to Check if a Number is Prime or Composite
Output when the entered number is a composite number
C Program to Check if a Number is Prime or Composite
Output when the entered number is a prime number

Do comment if you are confused in any steps.

Also Read: C Program to Check if a year is Leap or not

LEAVE A REPLY

Please enter your comment!
Please enter your name here