Write a C++ Program to Display Prime Numbers Between Two Intervals

In this tutorial, we will be discussing how to write a C++ program to display all the prime numbers between two given intervals.

A prime number is a positive integer greater than 1 that has no positive divisors other than 1 and itself.

To find all the prime numbers between two given intervals, we will use a nested loop.

The outer loop will iterate from the first number of the interval to the last number of the interval.

The inner loop will iterate from 2 to the current number of the outer loop. If the current number of the outer loop is divisible by any number in the inner loop, then it is not a prime number.

Otherwise, it is a prime number and will be displayed on the screen.

Let’s take a look at the C++ code:

#include <iostream>
using namespace std;

int main()
{
    int start, end, i, j, flag;
    cout << "Enter two numbers(intervals): ";
    cin >> start >> end;

    // Display all the prime numbers between start and end
    cout << "Prime numbers between " << start << " and " << end << " are: ";

    // Nested loop to find and display prime numbers
    for (i = start; i <= end; i++)
    {
        // Skip 0 and 1 as they are not prime numbers
        if (i == 1 || i == 0)
            continue;

        // Set the flag to 1 indicating the current number is a prime number
        flag = 1;

        for (j = 2; j <= i / 2; ++j)
        {
            if (i % j == 0)
            {
                flag = 0;
                break;
            }
        }

        if (flag == 1)
            cout << i << " ";
    }

    return 0;
}

First, we declare the variables start, end, i, j, and flag. We then prompt the user to enter the two numbers that define the interval.

Next, we display a message on the screen to indicate the prime numbers we will be displaying.

In the nested loop, we set i to start and iterate through each number in the interval.

If i is equal to 0 or 1, we skip it because those numbers are not prime. Otherwise, we set the flag to 1, indicating that the current number is a prime number.

In the inner loop, we set j to 2 and iterate through each number up to i / 2. If i is divisible by j, then the current number is not a prime number, and we set the flag to 0 and break out of the inner loop.

If the flag is still set to 1 after the inner loop, then the current number is a prime number, and we display it on the screen.

In conclusion, the above C++ program will find and display all the prime numbers between two given intervals using a nested loop.