Rectangle struct

Rectangle Struct

Define a Rectangle struct with member variables width and height. Add member functions float get_area() and float get_perimeter() to the struct to calculate the area and perimeter of the rectangle, respectively. Demonstrate them working.

Hint

Define the member functions inside the struct for easy access to the member variables.

Answer

#include <iostream>

struct Rectangle {
    float width;
    float height;

    float get_area() {
        return width * height;
    }

    float get_perimeter() {
        return 2 * (width + height);
    }
};

int main() {
    Rectangle myRectangle;

    std::cout << "Enter the width of the rectangle: ";
    std::cin >> myRectangle.width;

    std::cout << "Enter the height of the rectangle: ";
    std::cin >> myRectangle.height;

    std::cout << "Area of the rectangle: " << myRectangle.get_area() << std::endl;
    std::cout << "Perimeter of the rectangle: " << myRectangle.get_perimeter() << std::endl;

    return 0;
}
Questions