Learn how to write a C program to determine whether a given number is prime. This guide provides a step-by-step explanation of how to implement a function that checks for primality by testing divisibility from 2 up to the square root of the number. The tutorial includes sample code, explanations of the logic used, and tips for optimizing the program.
#include <stdio.h>
int main() {
int num, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &num);
for (i = 2; i <= num / 2; ++i) {
if (num % i == 0) {
flag = 1;
break;
}
}
if (num == 1) {
printf("1 is neither prime nor composite.\n");
}
else {
if (flag == 0)
printf("%d is a prime number.\n", num);
else
printf("%d is not a prime number.\n", num);
}
return 0;
}
Inside the main() function:
- An integer variable num is declared to store the input number.
- The user is prompted to enter a positive integer.
- A for loop is used to iterate from 2 to num/2.
- Within the loop, it checks if the number is divisible by any number other than 1 and itself.
- If the number is prime, it sets flag to 0, otherwise to 1.
- Finally, it prints whether the number is prime or not based on the value of flag.