Answer to Question #180088 in C++ for Naveen

Question #180088

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].



1
Expert's answer
2021-04-10T06:56:06-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

Naveen
10.04.21, 16:28

You Guys are awesome .Thanks for helping me

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS