Answer to Question #312465 in C++ for Vijay

Question #312465

1)WAP to print the sum and product of digits of an integer.


2)Create a class Box containing length, breath and height. Include following


methods in it:


a) Decrement, Overload -- operator (both prefix & postfix)


b) Overload operator==(to check equality of two boxes), as a friend function


c) Overload Assignment operator


d) Check if it is a Cube or cuboid Write a program which takes input from the user


for length, breath and height to test the above class.

1
Expert's answer
2022-03-16T07:09:21-0400

1.

#include <iostream>
using namespace std;

int main() {
    int a, b;


    cout << "Enter an integer: ";
    cin >> a;
    cout << "Enter another integer: ";
    cin >> b;


    cout << "The sum is " << a + b << endl;
    cout << "The product is " << a * b << endl;


    return 0;
}


2.

#include <iostream>
using namespace std;


class Box {
public:
    Box(int l=0, int b=0, int h=0);
    Box& operator=(const Box& b);
    Box& operator--();      // Prefix
    Box operator--(int);    // Postfix
    bool isCube() const;
    friend bool operator==(const Box& b1, const Box& b2);


private:
    int length;
    int breath;
    int height;
};


Box::Box(int l, int b, int h) 
{
    length = l>0 ? l : 0;
    breath = b>0 ? b : 0;
    height = h>0 ? h : 0;
}


Box& Box::operator=(const Box& b) 
{
    length = b.length;
    breath = b.breath;
    height = b.height;
    return *this;
}


Box& Box::operator--() 
{
    length = length > 0 ? --length : 0;
    breath = breath > 0 ? --breath : 0;
    height = height > 0 ? --height : 0;


    return *this;
}


Box Box::operator--(int) 
{
    Box tmp = *this;


    length = length > 0 ? --length : 0;
    breath = breath > 0 ? --breath : 0;
    height = height > 0 ? --height : 0;


    return tmp;
}


bool Box::isCube() const 
{
    return length == breath && length == height;
}


bool operator==(const Box& b1, const Box& b2)
{
    return b1.length == b2.length && 
           b1.breath == b2.breath && 
           b1.height == b2.height;
}


int main() {
    int l, b, h;


    cout << "Enter length, breath and height: ";
    cin >> l >> b >> h;


    Box box1(l, b, h);
    Box box2;


    box2 = box1;
    
    cout << "Test box2 = --box1" << endl;
    if (box2 == --box1) {
        cout << "True" << endl;
    }
    else {
        cout << "False" << endl;
    }


    box2 = box1;
    cout << "Test box2 = box1--" << endl;
    if (box2 == box1--) {
        cout << "True" << endl;
    }
    else {
        cout << "False" << endl;
    }


    if (box1.isCube()) {
        cout << "box1 is a cube" << endl;
    }
    else {
        cout << "box1 is not a cube" << endl;
    }


    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

No comments. Be the first!

Leave a comment