Display Prime Numbers Between Two Numbers Program in C Language

To find the prime numbers between two given numbers in C programming, we iterate from the smallest number to the highest number in increment of one, and check if the number is prime or not.

C Program

In the following program, we read two numbers to n1 and n2, and print the prime numbers present in the interval formed by these two numbers. We shall use C While Loop for iteration.

main.c

</>
Copy
#include <stdio.h>
#include <stdbool.h>

bool isPrime(int n) {
    bool isPrime = true;
    if (n == 0 || n == 1) {
        isPrime = false;
    }
    else {
        int i = 0;
        for (i = 2; i <= n / 2; ++i) {
            if (n % i == 0) {
                isPrime = false;
                break;
            }
        }
    }
    return isPrime;
}

int main() {
    int n1, n2;
    printf("Enter first  number : ");
    scanf("%d", &n1);
    printf("Enter second number : ");
    scanf("%d", &n2);
    
    int temp = (n1 > n2)? n2: n1;
    int upperlimit = (n1 > n2)? n1: n2;
    
    printf("Prime Numbers : ");
    while (temp < upperlimit) {
        if (isPrime(temp)) {
            printf("%d  ", temp);
        }
        temp++;
    }
    printf("\n");
}

Output

Enter first  number : 10
Enter second number : 20
Prime Numbers : 11  13  17  19  
Program ended with exit code: 0

Output

Enter first  number : 90
Enter second number : 150
Prime Numbers : 97  101  103  107  109  113  127  131  137  139  149  
Program ended with exit code: 0

Conclusion

In this C Tutorial, we learned how to display prime numbers in given interval in C programming, with examples.