Challenge: Rectangle Class

Lab C++ Beginner 10 points

Write a class Rectangle with private width and height, a constructor, and public methods area() and perimeter(). Read the width and height and print:

Area: 12
Perimeter: 14

Input

Two integers: width and height.

Output

Two lines, as above.

Example

Input

3 4

Output

Area: 12
Perimeter: 14
Sample input available Sample output available
Editor
C++

Hints

Put width and height under private:, and the constructor and methods under public:.

Perimeter is 2 * (width + height).

Solution explanation

The data is private, and the object answers questions about itself through its public methods.

Show solution
#include <iostream>
using namespace std;

class Rectangle {
private:
    int width;
    int height;

public:
    Rectangle(int w, int h) : width(w), height(h) {}

    int area() const {
        return width * height;
    }

    int perimeter() const {
        return 2 * (width + height);
    }
};

int main() {
    int w, h;
    cin >> w >> h;
    Rectangle r(w, h);
    cout << "Area: " << r.area() << "\n";
    cout << "Perimeter: " << r.perimeter() << "\n";
    return 0;
}
Output
Answer
HOME LABS COMMUNITY DASHBOARD