Create a class: “Prime” with private data members: upper_limit (int), lower_limit (int) and parameterized constructor, which initializes the values of both data members. Apart from initialization, this constructor also displays the count of prime numbers from upper_limit to lower_limit. [Example: upper_limit:15, lower_limit:10, count of prime numbers is:2(11 and 13), also make sure the value of upper_limit should be greater than lower_limit].
#include <iostream>
#include <string>
using namespace std;
class Prime{
private:
//private data members: upper_limit (int), lower_limit (int)
int upper_limit;
int lower_limit;
public:
//parameterized constructor, which initializes the values of both data members.
Prime(int upper_limit,int lower_limit){
this->upper_limit=upper_limit;
if(this->lower_limit<this->upper_limit){
this->lower_limit=lower_limit;
}else{
this->lower_limit=upper_limit;
}
//constructor also displays the count of prime numbers from upper_limit to lower_limit.
int count=0;
for (int number = this->lower_limit; number<= this->upper_limit; number++) {
bool isPrime=true;
if (number == 0 || number == 1) {
isPrime=false;
}else {
for (int i = 2; i <= number / 2; ++i) {
if (number % i == 0) {
isPrime=false;
break;
}
}
}
if(isPrime){
count++;
}
}
cout<<"The count of prime numbers: "<<count<<"\n";
}
~Prime(){}
};
int main (){
int upper_limit=0, lower_limit=0;
//Read upper limit from the user
cout<<"Enter upper limit: ";
cin>>upper_limit;
lower_limit=upper_limit;
//Read lower limit from the user
while(upper_limit<=lower_limit){
cout<<"Enter lower limit: ";
cin>>lower_limit;
}
//create Prime object
Prime prime(upper_limit,lower_limit);
return 0;
}
Comments
You Guys are awesome .Thanks for helping me
Leave a comment