C Program to Check Whether a Number is Prime or Not Using User Defined Function

Question: write a program in C language to read a number from a user and check whether it is a prime number or not using a user defined function.

A Prime Number is a positive integer greater than 1 which is divisible by 1 and itself. In other words, Prime number is a whole number greater than whose factors are 1 and itself. Examples of first few prime numbers are 2, 3, 5, 7, 11, 13..

Note : Number 2 is first and only even prime number.

This program checks whether a number given by a user is prime or not in c language using a user defined function.

Program


#include<stdio.h>
#include<conio.h>


#include

/* Function prototype to check prime number */
int check_prime(int n);

/* Main function */
int main()
{
	 int number, i, flag=0;

	 // Inputs
	 printf("Enter integer number: ");
	 scanf("%d", &number);

	 // Function call and taking decision
	 if(check_prime(number)==1)
	 {
	  	printf("%d is PRIME.", number);
	 }
	 else
	 {
	  	printf("%d is NOT PRIME.", number);
	 }

	 return(0);
}


int check_prime(int n)
{
    int i, flag=0;
    for(i=2;i<=n/2; i++)
	 {
		  if(n%i==0)
		  {
			   return 0;
		  }
	 }
	 return 1;
}

Output of above program :

Run 1:
-----------
Enter integer number: 13 ↲
13 is PRIME.

Run 2:
-----------
Enter integer number: 16 ↲
16 is NOT PRIME.

Run 3:
-----------
Enter integer number: 1 ↲
1 is NOT PRIME.

Run 4:
-----------
Enter integer number: 2 ↲
2 is PRIME.

Note: ↲ indicates enter is pressed.