C Program – Print Prime Numbers From 1 to N - Nested Loops & Optimized Check

Print Primes Using Nested Loops

#include <stdio.h>
int main() {
    int N, i, j, isPrime;
    printf("Enter the upper limit: ");
    scanf("%d", &N);
    printf("Prime numbers between 1 and %d are: ", N);
    for (i = 2; i <= N; i++) {
        isPrime = 1;
        for (j = 2; j < i; j++) {
            if (i % j == 0) {
                isPrime = 0;
                break;
            }
        }
        if (isPrime) {
            printf("%d ", i);
        }
    }
    printf("\n");
    return 0;
}
Enter the upper limit: 10
Prime numbers between 1 and 10 are: 2 3 5 7 
        

This straightforward approach checks each number from 2 up to the entered limit by dividing it by every smaller integer. If none divide evenly, the number is printed as prime.

Print Primes Using Optimized Check

#include <stdio.h>
#include <math.h>
int isPrime(int num) {
    int i;
    if (num <= 1) return 0;
    if (num == 2) return 1;
    if (num % 2 == 0) return 0;
    for (i = 3; i <= sqrt(num); i += 2) {
        if (num % i == 0) return 0;
    }
    return 1;
}
int main() {
    int N, i;
    printf("Enter the upper limit: ");
    scanf("%d", &N);
    printf("Prime numbers between 1 and %d are: ", N);
    for (i = 2; i <= N; i++) {
        if (isPrime(i)) {
            printf("%d ", i);
        }
    }
    printf("\n");
    return 0;
}
Enter the upper limit: 20
Prime numbers between 1 and 20 are: 2 3 5 7 11 13 17 19 
        

An optimized approach uses a helper function that checks divisibility only up to the square root of a number and skips even numbers after 2. Each number from 2 to N is tested with this function before being printed.

Sai Kishore Randhi, author
About the author

Sai Kishore Randhi

Embedded systems, VLSI, and chip design

Sai Kishore writes about embedded systems, VLSI, chip design, and the programming concepts behind modern hardware.

View LinkedIn profile ↗