Area and Perimeter of rectangle in C++

0
245
4 Big Mistakes to Avoid When Learning Programming
Binomial Coefficients in C++

area and perimeter of rectangle
Area and Perimeter both are the mathematical terms used with rectangle, area is the length multiplied by width while perimeter is the length of all sides of the rectangle. Now how we can implement area and perimeter of a rectangle in C++, In the below example we did it with the help of classes.


    #include<iostream>
    using namespace std;
    class Rectangle
    {
    private:
      
        float Length;
        float Width;
    public:
        Rectangle&setWidth(float);
        Rectangle&setLength(float);
        float area();
        float perimeter();
    };
    float Rectangle::perimeter()
    {
        return 2*(this->Length + this->Width);
    }
    Rectangle&Rectangle::setWidth(float Width)
    {
        this->Width = Width;
        return *this;
    }
    Rectangle&Rectangle::setLength(float Length)
    {
        this->Length = Length;
        return *this;
    }
    float Rectangle::area()
    {
        return this->Length * this->Width;
    }
     
    void main()
    {
    Rectangle R;
    cout<<R.setWidth(30).setLength(20).area();
    cout<<endl;
    cout<<R.perimeter();
    cout<<endl<<endl;
    system(“pause”);
    }


In the above code we defined a rectangle class with data members length and width, we have member functions for setwidth() and setlength() which sets the values of length and width, then we have functions for finding area and perimeter for the given length and width, the function area() finds the area by multiplying the length and width, while the function perimeter() returns the perimeter by adding all the sides. In our main() function we created an object of class rectangle, we set the values and then called the functions for area and perimeter.

4 Big Mistakes to Avoid When Learning Programming
Binomial Coefficients in C++

Leave a Reply