In this post, you will learn how to Display Prime Numbers Between Two Intervals in C++.
This lesson will teach you how to display Prime Numbers between two intervals, with a for loop, logical operator and decision making statement using the C++ Language. Let’s look at the below source code.
How to Display Prime Numbers Between Two Intervals?
RUN CODE SNIPPETSource Code
#include <iostream> using namespace std; int main() { int a, b, i, j, flag; cin >> a; cout << "Enter lower bound of the interval: "<<a; cin >> b; cout << "\nEnter upper bound of the interval: "<<b<<endl; cout << "\nPrime numbers between " << a << " and " << b << " are: "; for (i = a; i <= b; i++) { if (i == 1 || i == 0) continue; flag = 1; for (j = 2; j <= i / 2; ++j) { if (i % j == 0) { flag = 0; break; } } if (flag == 1) cout << i << " "; } return 0; }
Input
10 15
Output
Enter lower bound of the interval: 10 Enter upper bound of the interval: 15 Prime numbers between 10 and 15 are: 11 13
The statements #include<iostream>, using namespace std, int main are the main factors that support the function of the source code. Now we can look into the working and layout of the code’s function.
- Declare the variables a, b, i, j, flag an integers and collect the initial and final number; the upeer bound and lower bound from the user and store it in the a and b respectively using function
cin>>
and display the value usingcout<<
and the Insertion Operators'<<‘ , ‘>>’. - Create a for loop with the condition
(i = a; i <= b; i++)
, and then we create the loop statement. - Using the decision making if else statements we declare the condition to be verified. In the condition the logical operator OR is used. When both or any one of the sides of the conditions is true then the if condition is true, or it is false.
- The continue statement is used to force the loop to continue, if the if condition is true, the next iteration is executed if not it moves to the next statement.
- Create a for loop with the condition
(j = 2; j <= i / 2; ++j)
, and then we create the loop statement which includes an if statement with a condition to be verified. - When the condition is verified the body of the if statement is executed. Finally we add another if statement with a condition to be verified and an output statement.
Note: The ‘ << endl ‘ in the code is used to end the current line and move to the next line and ‘\n’ is also a new line function, to understand how both the functions work exclude it from the code, move it around and work with it.