Check if a Number is Prime in C Using Function
1. Introduction
Prime numbers are integers greater than 1 that have no divisors other than 1 and themselves. Checking for prime numbers using functions helps beginners understand modular programming in C.
2.Problem Statement
Question: Write a C program to check if a number is prime or not using a function.
3. Logic
To check whether a number is prime:
- Create a function that accepts an integer as input.
- Check if the number is less than 2; if yes, it is not prime.
- Loop from 2 to the square root of the number and check if any number divides it evenly.
- If no divisor is found, the number is prime; otherwise, it is not.
- Call the function from
main()and display the result.
4. Source Code
Here is a beginner-friendly C program using a function:
#include <stdio.h>
#include <math.h>
// Function to check prime
int isPrime(int num) {
if(num < 2)
return 0; // Not prime
for(int i = 2; i <= sqrt(num); i++) {
if(num % i == 0)
return 0; // Not prime
}
return 1; // Prime
}
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;
}
5. Sample Output
Enter a number: 17
17 is a prime number.
Enter a number: 20
20 is not a prime number.
6.Viva Questions
- Q: What is a prime number?
A: A prime number is greater than 1 and divisible only by 1 and itself. - Q: Why do we check up to the square root of the number?
A: Because if a number has a factor larger than its square root, the corresponding smaller factor will already be found. - Q: Can negative numbers be prime?
A: No, prime numbers are always positive integers greater than 1. - Q: What is the purpose of using a function here?
A: To modularize the code and make it reusable. - Q: What does
return 0in the function indicate?
A: That the number is not prime.
