Header Ad

HackerRank Rectangle Area solution in c++ programming

In this HackerRank Rectangle Area problem in the c++ programming language, you are required to compute the area of a rectangle using classes. Create two classes one is Rectangle and the second is RectangleArea.

  1. The Rectangle class should have two data fields-width and height of int types. The class should have a display() method, to print the width and height of the rectangle separated by space.
  2. The RectangleArea class is derived from the Rectangle class, i.e., it is the sub-class of the Rectangle class. The class should have the read_input() method, to read the values of width and height of the rectangle. The RectangleArea class should also overload the display() method to print the area (width X height) of the rectangle.

HackerRank Rectangle Area solution in c++ programming


HackerRank Rectangle Area problem solution in c++ programming.

#include <iostream>

using namespace std;
/*
 * Create classes Rectangle and RectangleArea
 */
 class Rectangle {
public:
    virtual void display() const {
        cout << width << ' ' << height << endl;
    }
    
protected:
    int width;
    int height;
};

class RectangleArea : public Rectangle {
public:
    void display() const override {
        cout << (width * height) << endl;
    }
    
    void read_input() {
        cin >> width >> height;
    }
};


int main()
{
    /*
     * Declare a RectangleArea object
     */
    RectangleArea r_area;
    
    /*
     * Read the width and height
     */
    r_area.read_input();
    
    /*
     * Print the width and height
     */
    r_area.Rectangle::display();
    
    /*
     * Print the area
     */
    r_area.display();
    
    return 0;
}


Second solution

#include <iostream>

using namespace std;
/*
 * Create classes Rectangle and RectangleArea
 */
 
 struct Rectangle {
    int w, h;
    void display() {
        printf("%d %d\n", w, h);
    }
};
struct RectangleArea : Rectangle {
    void read_input() {
        scanf("%d%d", &w, &h);
    }
    void display() {
        printf("%d\n", w * h);
    }
};



int main()
{
    /*
     * Declare a RectangleArea object
     */
    RectangleArea r_area;
    
    /*
     * Read the width and height
     */
    r_area.read_input();
    
    /*
     * Print the width and height
     */
    r_area.Rectangle::display();
    
    /*
     * Print the area
     */
    r_area.display();
    
    return 0;
}

Post a Comment

0 Comments