C++ Program to Print Prime numbers in a given range
Program to find Prime Numbers in a given range
Here we will discuss how to find prime numbers in the range specified by the user using C++ programming language.
Prime numbers are the numbers which have 2 divisors only i.e. the number that can be divided by 1 and the number itself then the number is a prime number.
Example: 2, 3, 5, 7, 11, 13………etc.
In this program, the user will specify a range and we will check for every number in the range for being prime
Let’s see how the code works:
- User gives two inputs(one for the lower limit & other for the upper limit).
- The inputs are stored in two int type variables say lowerLimit, upperLimit.
- Start a loop that will run from lowerLimit till upperLimit with every increment equal to 1
- For every value call a function prime() with that value as a parameter
- prime() will tell whether a number is prime or not
- Number of divisors of the number is found
- If the number of divisors is equal to 2 then the number is a prime number
- Otherwise the number is not a prime number.
- All the prime numbers between lowerLimit and upperLimit are printed.
//Prime numbers in a given range
using namespace std;
//function to chek for prime number
void prime(int num)
//checking for number of divisor
//no divisors other than 1 and itself
int lowerLimit, upperLimit;
cout<<"Prime numbers between "<<lowerLimit<<" and "<<upperLimit<<" are:"<<endl;
//finding prime numbers in the given range
Prime numbers between 1 and 20 are: