Q. C program to Check Whether a Number is Prime or not.

Here you will find an algorithm and program in C programming language to check whether the given number is prime number or not. First let us understand what prime number means.

Explanation : A number that is divisible by only and only 1 and itself is known as a Prime Number. For example: - 11 is only divisible by 1, so 11 is prime, while 10 is divisible by 1, 2, and 5 so 10 is not a prime number.

Prime Number Algorithm


START
  Step 1 → Take integer variable A
  Step 2 → Divide the variable A with (A/2 to 2)
  Step 3 → If A is divisible by any value (A/2 to 2) then it is not prime
  Step 4 → Else it is prime number
STOP


C Program to Check Whether a Number is Prime or Not

#include <stdio.h>
int main() {
	int n, i, flag = 0;
	printf("Enter a positive integer: ");
	scanf("%d", &n);
	for (i = 2; i <= n / 2; ++i) {
		if (n % i == 0) {
		flag = 1;
		break;
		}
	}
	if (n == 1) {
		printf("1 is neither prime nor composite.");
	}
	else {
		if (flag == 0)
			printf("This is a prime number.");
		else
			printf("This is not a prime number.");
	}
	return 0;
}

Output

Enter a positive integer : 17
This is a prime number.
Enter a positive integer : 25
This is not a prime number.