C Program to Display Prime Numbers Between Two Numbers

CodingTute

C Programming Examples

In this tutorial, you will learn how to display prime numbers between two numbers using C program.

Also Read: Check a Number is Prime or Not

C Program to Display Prime Numbers Beeeen Two Numbers

To write a C program to display the prime numbers between two intervals, you can use a function that takes in two integers as arguments and prints out all of the prime numbers within the specified range. Here is an example of how you can implement this function:

#include <stdbool.h>
#include <math.h>

bool is_prime(int n) {
    if (n <= 1) {
        return false;
    }
    for (int i = 2; i <= sqrt(n); i++) {
        if (n % i == 0) {
            return false;
        }
    }
    return true;
}

void display_primes(int lower, int upper) {
    for (int i = lower; i <= upper; i++) {
        if (is_prime(i)) {
            printf("%d\n", i);
        }
    }
}

int main() {
    int lower, upper;
    printf("Enter the lower bound: ");
    scanf("%d", &lower);
    printf("Enter the upper bound: ");
    scanf("%d", &upper);
    printf("The prime numbers between %d and %d are:\n", lower, upper);
    display_primes(lower, upper);
    return 0;
}
C

Output

Enter the lower bound: 10
Enter the upper bound: 56
The prime numbers between 10 and 56 are:
11
13
17
19
23
29
31
37
41
43
47
53

Explanation

The display_primes() function uses a loop to iterate through the integers from the lower bound to the upper bound, and for each integer it calls the is_prime() function to determine if it is a prime number. If the number is prime, it is printed out.

The is_prime() function uses a loop to iterate through the integers from 2 to the square root of the number, and checks if the number is divisible by any of these integers using the modulus operator (%). If the number is divisible by any of these integers, the function returns false because it is not prime.

If the loop completes without finding a divisor, the function returns true because the number is prime. This process continues until all of the integers in the specified range have been checked, and the prime numbers are printed out.

You can find more C Programming Examples here.

Follow us on Facebook, YouTube, Instagram, and Twitter for more exciting content and the latest updates.