C++ program to find the area of a rectangle

C++ program to find the area of a rectangle:

In this blog post, we will learn how to find the area of a rectangle with user-input values. We need to get the length and breadth of the rectangle to find its area. I will show you how to write a C++ program to find the rectangle area in two different ways.

Algorithm to find the rectangle area:

We can follow the below algorithm to calculate the area:

  • Take the length and breadth of the rectangle as inputs from the user.
  • Multiply these values to find the rectangle area and assign it to a different variable.
  • Print the rectangle area to the user.

Example 1: C++ program to find the rectangle area:

Below is the complete program:

#include <iostream>
using namespace std;

int main()
{
    float length, breadth, area;

    cout << "Enter the length of the rectangle: " << endl;
    cin >> length;

    cout << "Enter the breadth of the rectangle: " << endl;
    cin >> breadth;

    area = length * breadth;

    cout << "Area of the rectangle: " << area << endl;
}

Here,

  • It asks the user to enter the length and breadth of the rectangle and assigns these values to the length and breadth float variables.
  • The area of the rectangle is calculated by multiplying the length and breadth. It is assigned to the float variable area.
  • The last line is printing the calculated area.

It will print output as below:

Enter the length of the rectangle: 
12
Enter the breadth of the rectangle: 
22.3
Area of the rectangle: 267.6

Example 2: C++ program to find the rectangle area by using a separate function:

Let’s use a separate function to find the rectangle area. The main function will call this function to calculate the area and it will print the calculated value.

#include <iostream>
using namespace std;

float findArea(float length, float breadth)
{
    return length * breadth;
}

int main()
{
    float length, breadth, area;

    cout << "Enter the length of the rectangle: " << endl;
    cin >> length;

    cout << "Enter the breadth of the rectangle: " << endl;
    cin >> breadth;

    area = findArea(length, breadth);

    cout << "Area of the rectangle: " << area << endl;
}

We created a new function findArea to calculate the area. This function takes the length and breadth of the rectangle as its parameters and returns the area.

It is better to use a separate function always because we can call this function from any other place to get the same result.

C++ find the area of a rectangle