Check for Prime Numbers using Loops in C
To check whether a number is prime in C, we use loops to test if it is divisible by any number other than 1 and itself. A prime number has exactly two divisors: 1 and itself. We can implement this check using for
or while
loops, iterating through possible divisors up to a certain limit.
Examples to Check Prime Numbers
1. Checking Prime Number Using a for
Loop
In this example, we check if a given number is prime using a for
loop. We iterate from 2 to num/2
and check if the number is divisible by any value. If it is, the number is not prime.
main.c
</>
Copy
#include <stdio.h>
int main() {
int num, isPrime = 1;
printf("Enter a number: ");
scanf("%d", &num);
if (num <= 1) {
isPrime = 0;
} else {
for (int 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;
}
Explanation:
- We declare
num
for input andisPrime
initialized to 1 (true). - We take user input using
scanf()
. - If
num
is less than or equal to 1, we mark it as not prime. - We use a
for
loop to check divisibility from2
tonum/2
. - If we find a divisor, we set
isPrime
to 0 and break the loop. - We print whether the number is prime based on
isPrime
‘s value.
Output:
Enter a number: 7
7 is a prime number.
2. Checking Prime Number Using a while
Loop
In this example, we use a while
loop instead of a for
loop to check if a number is prime. We incrementally divide the number by values starting from 2.
main.c
</>
Copy
#include <stdio.h>
int main() {
int num, i = 2, isPrime = 1;
printf("Enter a number: ");
scanf("%d", &num);
if (num <= 1) {
isPrime = 0;
} else {
while (i <= num / 2) {
if (num % i == 0) {
isPrime = 0;
break;
}
i++;
}
}
if (isPrime)
printf("%d is a prime number.\n", num);
else
printf("%d is not a prime number.\n", num);
return 0;
}
Explanation:
- We initialize
i
to 2 andisPrime
to 1. - We take user input using
scanf()
. - If
num
is ≤ 1, we mark it as not prime. - The
while
loop runs from 2 tonum/2
. - If
num
is divisible by anyi
, we setisPrime
to 0 and break. - Finally, we print whether the number is prime based on
isPrime
.
Output:
Enter a number: 12
12 is not a prime number.
Conclusion
We explored different methods to check if a number is prime in C:
- Using a
for
loop: Iterates through possible divisors up tonum/2
. - Using a
while
loop: Achieves the same check but with awhile
condition.