Read the question, write C++ on the right, then Run or Check.
QuestionHint and solution stay closed until you open them
Read a width and a height. Build a Rectangle class with area() and perimeter() methods and print both.
Print two lines exactly: "Area: X" then "Perimeter: Y".
Input. Two integers: width then height.
Output. Line 1: Area: <area>. Line 2: Perimeter: <perimeter>.
Constraints
- 1 ≤ width, height ≤ 10000
Examples
Input
4 3
Output
Area: 12 Perimeter: 14
Hint
- Store w and h as members. area() returns w * h; perimeter() returns 2 * (w + h).
Show correct code
Peek only after you have tried. You can still Check your own version.
#include <iostream>
class Rectangle {
public:
int w, h;
Rectangle(int width, int height) : w(width), h(height) {}
int area() const { return w * h; }
int perimeter() const { return 2 * (w + h); }
};
int main() {
int w, h;
std::cin >> w >> h;
Rectangle r(w, h);
std::cout << "Area: " << r.area() << "\n";
std::cout << "Perimeter: " << r.perimeter() << "\n";
return 0;
}
main.cppC++17 · g++ · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.