Display Prime Numbers Between Two Intervals Using C++

03-11-17 Course- CPP

This program asks user to enter first and second integer and this program will display all prime numbers between these intervals. If you don't know how to check whether a number is prime or not then, this program may seem little bit complex. 

Source Code to Display Prime Numbers Between two Intervals


/* C++ program to display all prime numbers between Two interval entered by user. */
#include <iostream>
#include <iomanip>
#include <cmath>
int main()
{
    int num1, num2, count, n;
    cout << "Enter first number: ";
    cin >> num1;
    cout << "Enter second number: ";
    cin >> num2;

    cout << "The prime numbers between " << num1 << " and " << num2 << " are: " << endl;
    for (n = num1; n <= num2; n++){
        count = 0;
        for (int i = 2; i <= n/2; i++){
            if(n%i==0){
                count++;
                break;
            }
        }
        if(count==0 && n!=1){
            cout << n << endl;
        }
    }
    return 0;
}

Output


Enter first number: 1
Enter second number: 10
The prime numbers between 1 and 10 are: 
2
3
5
7

In this program, it is assumed that, the user always enters smaller number first. This program will not perform the task intended if user enters larger number first. You can add the code to swap two numbers entered by user if user enters larger number first to make this program work properly.