Introduction:
A prime number is a number greater than 1 that has no positive divisors other than 1 and itself. In other words, a prime number cannot be divided evenly by any other number except for 1 and the number itself. For example, 2, 3, 5, 7, 11, and 13 are prime numbers.
Objective:
The objective of this program is to determine whether a given number is prime or not. The program will take an integer as input, check if it has any divisors other than 1 and itself, and then output whether the number is prime or not.
Code:
#include
// Function to check if a number is prime
int isPrime(int num) {
if (num <= 1) {
return 0; // Numbers less than or equal to 1 are not prime
}
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
return 0; // If the number is divisible by i, it is not prime
}
}
return 1; // If no divisors were found, the number is prime
}
int main() {
int num;
// Ask the user to input a number
printf("Enter a number to check if it is prime: ");
scanf("%d", &num);
// Check if the number is prime and display the result
if (isPrime(num)) {
printf("%d is a prime number.\n", num);
} else {
printf("%d is not a prime number.\n", num);
}
return 0;
}
Explanation of the Program:
The program is structured into two main parts:
- Function to check prime: The
isPrime
function takes an integer as input and returns 1 if the number is prime and 0 otherwise. It uses a loop to check if the number is divisible by any number from 2 to the square root of the number. If it finds any divisor, it returns 0, indicating the number is not prime. If no divisors are found, it returns 1, indicating the number is prime. - Main function: In the
main
function, the program prompts the user to enter a number. This number is then passed to theisPrime
function. Based on the result, the program prints whether the number is prime or not.
How to Run the Program:
Follow these steps to run the program:
-
- Write the code in a file with a
.c
extension, for example,prime_check.c
. - Compile the program using a C compiler like
gcc
. Open your terminal or command prompt and type:
- Write the code in a file with a
gcc prime_check.c -o prime_check
-
- Run the compiled program by typing:
./prime_check
- The program will prompt you to enter a number. After entering the number, it will check and display whether the number is prime or not.