C Program – Display Prime Numbers Between Intervals - Range Prime Finder

Display Prime Numbers Between Intervals

This program lists all prime numbers between two positive integers supplied by the user. It iterates through every integer in the interval, tests whether it is prime by checking divisibility up to its square root, and prints it if it has no divisors other than 1 and itself.

#include <stdio.h>
int main() {
    int low, high;
    printf("Enter two positive integers (lower and upper interval): ");
    scanf("%d %d", &low, &high);
    printf("Prime numbers between %d and %d are:\n", low, high);
    for (int num = low; num <= high; num++) {
        if (num < 2) continue;    // Skip 0 and 1
        int isPrime = 1;          // Assume num is prime
        for (int i = 2; i * i <= num; i++) {
            if (num % i == 0) {
                isPrime = 0;      // Found a divisor, num is not prime
                break;
            }
        }
        if (isPrime) {
            printf("%d ", num);
        }
    }
    printf("\n");
    return 0;
}
Enter two positive integers (lower and upper interval): 10 30
Prime numbers between 10 and 30 are:
11 13 17 19 23 29 
        

The outer loop iterates over each integer in the specified interval, and the inner loop tests whether the current number is divisible by any value between 2 and its square root. If no divisor is found, the number is printed as prime. Numbers less than 2 are skipped because primes start at 2.


Comments

💬 Please keep your comment relevant and respectful. Avoid spamming, offensive language, or posting promotional/backlink content.
All comments are subject to moderation before being published.


Loading comments...