Area and Perimeter of Rectangle in C++

Area and perimeter of a rectangle in C++ from length and width.

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}

Output

Enter length of rectangle: 5
Enter width of rectangle: 3
Area of rectangle = 15 square units
Perimeter of rectangle = 16 units

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.