Introduction
In number theory, a prime number is a number greater than 1 that has no divisors other than 1 and itself. Detecting whether a number is prime is a foundational concept in programming. This post provides a simple and efficient C program to check whether the given number is prime or not.
Problem Statement
Write a C program that takes an integer input from the user and checks if it is a prime number. A prime number should be divisible only by 1 and itself.
C Program to Check Prime Number
#include <stdio.h>
int main() {
int num, i, isPrime = 1;
printf("Enter a number: ");
scanf("%d", &num);
if (num <= 1) {
isPrime = 0;
} else {
for (i = 2; i <= num / 2; i++) {
if (num % i == 0) {
isPrime = 0;
break;
}
}
}
if (isPrime)
printf("%d is a Prime Number.\n", num);
else
printf("%d is Not a Prime Number.\n", num);
return 0;
}
Code Explanation
- Input: The user provides an integer number.
- Prime Check Logic:
- If the number is less than or equal to 1, it’s not a prime.
- The loop checks divisibility from 2 to
num/2
. - If divisible by any number in that range, it’s not a prime.
- Output: Displays whether the number is prime or not.
Sample Output
Enter a number: 7
7 is a Prime Number.
Enter a number: 12
12 is Not a Prime Number.
Why Use This Code
This program is useful for understanding how loops and conditionals work together. It is often used in introductory computer science and competitive programming tasks.
Conclusion
The C program to check prime number demonstrates fundamental logic and control flow. Understanding prime number logic is essential in many areas of algorithm development, including encryption and data processing.