C Program to print all prime numbers till 20
Objective
Write a C program to print all prime numbers up to 20.
Algorithm / Approach
- Run an outer loop
nfrom 2 up to 20. - For each number, initialize a
factors = 0counter. - Run an inner loop
ifrom 1 ton. - If
n % i == 0, increment thefactorscounter. - After the inner loop, if
factors == 2, the number is Prime, so print it.
main.c
#include<stdio.h>
int main( ) {
int i, j, factors;
for(n=2; j<=20; n++) {
factors = 0;
for(i=1; i<=n ; i++) {
if(n%i == 0) {
factors++
}
}
if(factors == 2) {
printf("%d ",n);
}
} return 0;
}
Expected Output
2 3 5 7 11 13 17 19
Explanation of the Program
- A Prime number has exactly two distinct factors: 1 and itself.
- We use an outer loop to generate the numbers from 2 to 20. For each number, we use an inner loop to physically count how many numbers can divide it cleanly. If that count is exactly 2, we know for a fact it is prime.
Complexity
Time Complexity
O(n^2) - Or exactly O(M*M) where M is the upper bound (20).
Space Complexity
O(1)
Common Mistakes
- Writing
j <= 20in the outer loop but never defining or incrementingj. This causes an infinite loop or compiler error depending on the compiler. Ensure the loop variable matches (e.g.,n <= 20).