Program to Find the Perimeter of a Rectangle

Learn via video courses
Topics Covered

In our school days, we must have calculated the perimeter of different shapes in our Math classes. In simple terms, perimeter simply means the boundary of a closed figure. Like for example the perimeter of our country India will be the length of the entire border or coastline. Now let us understand how we calculate the perimeter of a rectangle.

Algorithm to Calculate Perimeter of Rectangle

For calculating the perimeter of a rectangle we will need its length and its breadth. We have two variables, L and B, that stores the length and breadth respectively.

Length of rectangle = L

Breadth of rectangle = B

algorithm to calculate perimeter of rectangle Now in the rectangle ABCD given above, we can see that sides AB and CD denote the length, whereas sides BC and DA denote the breadth. Thus we can say that,

AB = L and CD = L
BC = B and DA = B

So now we need to find the length of the boundary of this closed figure (rectangle ABCD) to find its perimeter. Thus the perimeter will be the sum of all sides of the rectangle, i.e.

Perimeter = AB + BC + CD + DA
=> L + B + L + B
=> 2 * (L + B)

Hence we can say that the perimeter of a rectangle can be calculated by the formula twice the sum of length and breadth.

Solution

So now we will see the code to calculate the perimeter of a rectangle by taking in length and breadth as inputs, and we will simply print the perimeter as output. We will see this code in multiple languages.

Python Code

Java Code

C++ Code

C# Code

PHP Code

Complexity

Now let us calculate the Time and Space complexity of the code mentioned above to find the perimeter of a rectangle.

We are performing a mathematical operation, i.e., 2 * (l + b) for finding the perimeter, and hence the Time Complexity is O(1).

We are using just variables to perform the mathematical calculation and are not taking any extra auxiliary space in our program. Hence the Space Complexity is also O(1).

Let us now take an example and analyze our code.

time complexity of perimeter of a rectangle In the figure given above, we have a rectangle ABCD with dimensions 5 X 3, i.e.,

Length = 5
Breadth = 3

We already know that the perimeter of a rectangle is 2 * (L + B), thus by using this equation we get

Perimeter = 2 * (5 + 3)
=> 2 * 8
=> 16

Hence the perimeter of the rectangle ABCD is 16.

Conclusion

The use cases of the perimeter of any figure is very subjective since it is a mathematical tool we use depending upon the problem statement we are dealing with. A few common use cases of the perimeter are:

  • Solving Mensuration problems in mathematics.
  • Dealing with problems involving Computational Geometry.