Unlocking the Power of C++: A Deep Dive into Prime Number Generation

The Foundation: C++ Conditional Statements

Before diving into the examples, it’s essential to have a solid grasp of C++ conditional statements, including if, if...else, and nested if...else constructs. These statements form the backbone of decision-making in C++ programming.

Example 1: Unleashing Prime Numbers with a While Loop

Imagine a program that displays all prime numbers between two user-defined intervals. This C++ program employs a while loop that iterates (high - low - 1) times, checking whether each number in the range is prime or not. With each iteration, the value of low increments by 1 until it reaches high. But what happens when the user enters the larger number first? The program doesn’t work as intended! Fear not, for we can solve this issue by simply swapping the numbers if the user enters them in the wrong order.

int main() {
    int low, high;
    cout << "Enter lower limit: ";
    cin >> low;
    cout << "Enter upper limit: ";
    cin >> high;

    if (low > high) {
        int temp = low;
        low = high;
        high = temp;
    }

    cout << "Prime numbers between " << low << " and " << high << " are: ";
    while (low <= high) {
        if (isPrime(low)) {
            cout << low << ", ";
        }
        low++;
    }
    cout << endl;
    return 0;
}

Output: Prime Numbers Between Two Intervals

Take a look at the output of this program:

Enter lower limit: 10
Enter upper limit: 20
Prime numbers between 10 and 20 are: 11, 13, 17, 19

Curious about how to check whether a number is prime or not? You can learn more about prime number checks.

Example 2: Displaying Prime Numbers with a Twist

What if we want to display prime numbers between two intervals, but with a user-defined function? This program tackles the challenge head-on, showcasing the power of C++ in generating prime numbers even when the larger number is entered first.

bool isPrime(int num) {
    if (num <= 1) return false;
    for (int i = 2; i * i <= num; i++) {
        if (num % i == 0) return false;
    }
    return true;
}

void displayPrimes(int low, int high) {
    if (low > high) {
        int temp = low;
        low = high;
        high = temp;
    }

    cout << "Prime numbers between " << low << " and " << high << " are: ";
    while (low <= high) {
        if (isPrime(low)) {
            cout << low << ", ";
        }
        low++;
    }
    cout << endl;
}

int main() {
    int low, high;
    cout << "Enter lower limit: ";
    cin >> low;
    cout << "Enter upper limit: ";
    cin >> high;

    displayPrimes(low, high);
    return 0;
}

Output: Prime Numbers with a User-Defined Function

Check out the output of this program:

Enter lower limit: 20
Enter upper limit: 10
Prime numbers between 10 and 20 are: 11, 13, 17, 19

Want to learn more about displaying all prime numbers between two intervals using a user-defined function? You can discover the secret.

Leave a Reply