Implement a number class to represent integers in accordance with the following
ID: 3846930 • Letter: I
Question
Implement a number class to represent integers in accordance with the following UML class
diagram.
+-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -+
| |
| Number |
| |
+-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -+
| |
| - n : int |
| |
+-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -+
| |
| + Number(n : int) |
| + setValue(n : int) |
| + isPrime() : bool |
| + isLucky() : bool |
| |
+-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -+
The number class represents integers. The integer value it represents is passed into the
constructor and stored in member variable n. The setValue function takes an integer argument,
which it copies into it's private member variable n. The isPrime function returns true if member
variable n is prime and false if not prime. The isLucky function returns true if the member
variable n is divisible by 7.
In the main function of your program, provide test code for the isPrime and isLucky functions.
Use assert statements for this purpose. Make sure that your test code executes every line of code
in the 2 functions.
Explanation / Answer
PROGRAM CODE:
#include <iostream>
#include <assert.h>
using namespace std;
//Number class
class Number
{
//memeber variable - n
private:
int n;
public:
Number(int n)
{
setValue(n);
}
void setValue(int n)
{
this->n = n;
}
//function to check if the number is prime
bool isPrime()
{
int limit = (int)n/2;
for(int i=2; i<limit; i++)
{
if(n%i == 0)
return false;
}
return true;
}
//function to check if the number is lucky
bool isLucky()
{
if(n%7 == 0)
return true;
else return false;
}
};
int main() {
Number n1(7);
assert(n1.isPrime() == true);
cout<<"Number 7 is prime"<<endl;
assert(n1.isLucky() == true);
cout<<"Number 7 is lucky"<<endl;
Number n2(13);
assert(n2.isPrime() == true);
cout<<"Number 13 is prime"<<endl;
assert(n2.isLucky() == false);
cout<<"Number 13 is not lucky"<<endl;
Number n3(15);
assert(n3.isPrime() == false);
cout<<"Number 15 is not prime"<<endl;
assert(n3.isLucky() == false);
cout<<"Number 15 is not lucky"<<endl;
return 0;
}
OUTPUT:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.