CodeRush Sale · 60% off all certificate courses until 15 Dec

Area and Perimeter of Rectangle in C++

Find the area and perimeter of a rectangle from length and width in C++. Practice two formulas, float input, and why 2 * (l + w) needs its parentheses.

BeginnerBasic ProgramsExample 12 of 14
area-and-perimeter-of-rectangle.cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 float length, width, area, perimeter;
6
7 cout << "Enter length of rectangle: ";
8 cin >> length;
9
10 cout << "Enter width of rectangle: ";
11 cin >> width;
12
13 area = length * width;
14 perimeter = 2 * (length + width);
15
16 cout << "Area of rectangle = " << area << " square units" << endl;
17 cout << "Perimeter of rectangle = " << perimeter << " units" << endl;
18
19 return 0;
20}

Sample Output

Area of rectangle = 15 square units

5 × 3.

Perimeter of rectangle = 16 units

2 × (5 + 3).

In this one

  • How to compute area as length × width
  • How to compute perimeter as 2 × (length + width)
  • Why parentheses change the perimeter result
  • How to label units in output

How it works

  1. 1

    Read length and width as float (5 and 3).

  2. 2

    area = 5 × 3 = 15.

  3. 3

    perimeter = 2 × (5 + 3) = 16.

  4. 4

    Print each value with its unit label.

Edge cases

Zero width

Enter 0 for width.

Area becomes 0 and perimeter becomes 2 × length. The math runs, but the shape is a line, not a rectangle.

Decimal sides

Enter 2.5 and 4.

float keeps the fraction: area 10, perimeter 13. With int variables, 2.5 would be read as 2.

What's going on

This C++ program reads length and width, then prints area (length * width) and perimeter (2 * (length + width)).

float length, width, area, perimeter;

float so 5.5 still works. Integers are fine if the problem only uses whole numbers.

cin >> length; then cin >> width;

Sample: 5 and 3.

area = length * width;

5 * 3 = 15.

perimeter = 2 * (length + width);

2 * (5 + 3) = 16. The parentheses matter. 2 * length + width is 13, which is not a perimeter.

Those formulas assume a rectangle: sides meet at right angles. A diagonal is not a width.

Negative length still multiplies. The math runs; the answer is still nonsense. Check < 0 if the input can be bad.

The cout lines label square units vs units. Swap those two prints and the output is confidently wrong.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

length = 4, width = 2. What does 2 * length + width give?

Pick an answer to check it.

Question 2

What is the area for length 6 and width 0.5?

Pick an answer to check it.

Questions people ask

Why are there no decimals in the output?

cout prints 15 instead of 15.0 by default when the value is a whole number. Add fixed and setprecision to force decimals.

How would I do a square?

Use one side: area = side * side, perimeter = 4 * side.

Can I compute the diagonal?

Yes: sqrt(length*length + width*width) with <cmath>.