In this C++ programming example, we will write a C++ Program to display Prime Numbers between two intervals. Let us start by understanding what is a prime number.
Prime Number:
A Prime Number is a number that is only divisible by 1 and itself. Example: 2, 3, 5, 7, 11, 13, 17, etc. These numbers are only divisible by 1 and the number itself.
Note:
0 and 1 is not a prime number and 2 is the only even and smallest prime number.
To understand the following program, you should have a basic idea about the following topics in C++ programming.
C++ Program to Print Prime Numbers
The program takes the user input for the starting number ( lower range) and the end number (upper range). Then prints all the prime numbers that fall within that range.
Also notice in the program that 0 and 1 are specifically checked to make sure that those two are not printed even if the lower range entered by the user is 0.
Print Prime Numbers in a Given Range in C++.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | #include <iostream> using namespace std; int main() { int lrRange, upRange, i, flag; cout << "Enter the lower range: "; cin >> lrRange; cout << "Enter the upper range: "; cin >> upRange; cout << "\nList of Prime numbers between " << lrRange << " & " << upRange << ": " << endl; while (lrRange < upRange) { flag = 0; // checking for 0 and 1 if (lrRange == 0 || lrRange == 1) { flag = 1; } else { for (i = 2; i <= lrRange / 2; ++i) { if (lrRange % i == 0) { flag = 1; break; } } } if (flag == 0) cout << lrRange << " "; ++lrRange; } return 0; } |
Output:
Enter the lower range: 0
Enter the upper range: 30
List of Prime numbers between 0 & 30:
2 3 5 7 11 13 17 19 23 29
You can also print the prime numbers between 0 to any range or 100 using the same logic as above. You may go through the following program for more.