C++ Program to Display Prime Numbers Between Two Intervals Using Function

18/05/2024 0 By indiafreenotes

Creating a C++ program that displays prime numbers between two intervals using a function involves defining a function to check if a number is prime and then using this function to list all prime numbers within a given range specified by the user.

C++ Code:

#include <iostream>

using namespace std;

// Function to check if a number is prime

bool isPrime(int num) {

    if (num <= 1) {

        return false; // 0 and 1 are not prime numbers

    }

    for (int i = 2; i * i <= num; i++) {

        if (num % i == 0) {

            return false; // Found a divisor, not a prime number

        }

    }

    return true; // No divisors found, it’s a prime number

}

// Function to print all prime numbers in a given range

void displayPrimes(int low, int high) {

    cout << “Prime numbers between ” << low << ” and ” << high << ” are:” << endl;

    for (int i = low; i <= high; i++) {

        if (isPrime(i)) { // Use the isPrime function to check primality

            cout << i << ” “;

        }

    }

    cout << endl;

}

int main() {

    int low, high;

    // Asking the user for the range

    cout << “Enter the lower bound of the range: “;

    cin >> low;

    cout << “Enter the upper bound of the range: “;

    cin >> high;

    // Displaying prime numbers in the given range

    displayPrimes(low, high);

    return 0;

}

Explanation:

  • Function isPrime(int num):

This function checks if a number is prime. It returns false for numbers less than 2. For all other numbers, it checks divisibility from 2 up to the square root of the number. If any divisor is found, it returns false. If no divisors are found, it returns true.

  • Function displayPrimes(int low, int high):

This function uses the isPrime function to check and print all prime numbers between the provided lower (low) and upper (high) bounds. It iterates from low to high, and for each number, it calls isPrime to determine if it should be printed.

  • Main Function:

main function prompts the user to enter the lower and upper bounds of the range. It then calls displayPrimes to display the prime numbers within that range.

Sample Output:

For user inputs low = 10 and high = 30, the output will be:

Enter the lower bound of the range: 10

Enter the upper bound of the range: 30

Prime numbers between 10 and 30 are:

11 13 17 19 23 29

This program effectively demonstrates the use of functions to break down the task of identifying prime numbers and presenting them within a specified range, showcasing a clear structure and promoting code reusability.