Program using a nested for loop to find the prime numbers from 2 to 20
#include <stdio.h>
int main() {
int i, j, isPrime;
printf("Prime numbers from 2 to 20 are:\n");
for (i = 2; i <= 20; i++) { // Outer loop: check each number from 2 to 20
isPrime = 1; // Assume i is prime
for (j = 2; j < i; j++) { // Inner loop: check if i is divisible by any number less than i
if (i % j == 0) {
isPrime = 0; // Not a prime number
break; // No need to check further
}
}
if (isPrime) {
printf("%d ", i); // Print prime number
}
}
return 0;
}
OUTPUT
Prime numbers from 2 to 20 are:
2 3 5 7 11 13 17 19
Explanation:
-
Outer Loop (
for (i = 2; i <= 20; i++)):-
Checks every number from 2 to 20.
-
-
Inner Loop (
for (j = 2; j < i; j++)):-
Checks if
iis divisible by any number other than 1 and itself. -
If divisible,
isPrimeis set to 0 (false) and loop breaks.
-
-
isPrimeFlag:-
If still 1 after the inner loop, the number is prime and is printed.
-
What Is a Prime Number?
A prime number is a number greater than 1 that has no divisors other than 1 and itself.


