Introduction
Determining whether a number is prime is a common problem in computer science. In this article, you will learn how to write a function in C to check if a number is prime. The function will return 1
if the number is prime, otherwise 0
.
C Program to Check If a Number is Prime Using Function
#include <stdio.h>
int isPrime(int num) {
if (num <= 1)
return 0;
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0)
return 0;
}
return 1;
}
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);
if (isPrime(number))
printf("%d is a prime number.\n", number);
else
printf("%d is not a prime number.\n", number);
return 0;
}
Explanation
- The function
isPrime()
checks if a number is divisible by any number from 2 tonum / 2
. - If any such divisor exists, the number is not prime (
return 0
). - If no divisor is found, the number is prime (
return 1
). - The
main()
function takes user input and prints the result using the return value from the function.
Sample Output
Enter a number: 7
7 is a prime number.
Enter a number: 12
12 is not a prime number.
Use Cases
- Checking prime numbers for cryptography, number theory, or competitive programming.
- Helps in understanding functions, conditionals, and loops in C programming.