Skip to content
Devtoolry

Numbers · intermediate

C Program to Print Prime Numbers in a Range

Print all prime numbers between two numbers in C with nested loops and a flag variable, then with the Sieve of Eratosthenes using an array of flags.

Printing the primes in an interval combines an outer loop over the candidates with an inner loop that looks for a divisor. A flag variable remembers whether a divisor was found, and break stops the inner loop as soon as one is.

The program

C
#include <stdio.h>

int main(void) {
    int low = 10, high = 50;

    for (int n = low < 2 ? 2 : low; n <= high; n++) {
        int is_prime = 1;
        for (int d = 2; d * d <= n; d++) {
            if (n % d == 0) {
                is_prime = 0;
                break;
            }
        }
        if (is_prime)
            printf("%d ", n);
    }
    printf("\n");
    return 0;
}
Output
11 13 17 19 23 29 31 37 41 43 47 

How it works

  1. The outer loop visits each candidate from low (at least 2) to high.
  2. is_prime starts as 1 (true) for every candidate.
  3. The inner loop tries divisors up to √n; finding one sets the flag to 0 and break leaves the inner loop.
  4. Only candidates whose flag is still 1 are printed, each followed by a space; the final printf ends the line.

Another way: Sieve of Eratosthenes

Instead of testing each number, cross out multiples of every prime. The array composite[] marks crossed-out numbers. Static storage (outside main) keeps a large array off the stack.

C
#include <stdio.h>

#define LIMIT 50
static char composite[LIMIT + 1];

int main(void) {
    for (int p = 2; p * p <= LIMIT; p++) {
        if (!composite[p]) {
            for (int m = p * p; m <= LIMIT; m += p)
                composite[m] = 1;
        }
    }
    for (int n = 10; n <= LIMIT; n++) {
        if (!composite[n])
            printf("%d ", n);
    }
    printf("\n");
    return 0;
}
Output
11 13 17 19 23 29 31 37 41 43 47 

Common mistakes

  • Declaring is_prime outside the outer loop without resetting it, so after the first non-prime every number is skipped.
  • Forgetting break: correct, but the inner loop keeps dividing after the answer is known.
  • Declaring a sieve of millions of chars inside main, which can overflow the stack. Make it static or allocate it with malloc.

Try it yourself

  • Read low and high with scanf.
  • Print twin primes (pairs that differ by 2) below 100.

Open the program in the C Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.

Browse all 25 C examples, or write your own program in the online C Compiler.