Challenge: Rectangle Class
Completed
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
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
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module