Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to print all prime numbers till 20

C Code Example — Series Programs

ADVERTISEMENT

C Program to print all prime numbers till 20

Objective

Write a C program to print all prime numbers up to 20.

Algorithm / Approach

  1. Run an outer loop n from 2 up to 20.
  2. For each number, initialize a factors = 0 counter.
  3. Run an inner loop i from 1 to n.
  4. If n % i == 0, increment the factors counter.
  5. 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 <= 20 in the outer loop but never defining or incrementing j. This causes an infinite loop or compiler error depending on the compiler. Ensure the loop variable matches (e.g., n <= 20).
ADVERTISEMENT