Calculate the Perimeter of a Rectangle

Calculate the Perimeter of a Rectangle in C++

Strengthen your understanding of arithmetic operators and variable management by building a program that computes the total distance around a rectangle.

Logic and Geometry

The Perimeter Formula

The perimeter is the sum of all sides. For a rectangle, we use the formula $P = 2 \cdot (length + width)$ or $P = (2 \cdot length) + (2 \cdot width)$.

Multiple Inputs

This exercise practices capturing two distinct values from the user and storing them in separate variables before performing calculations.

Step-by-Step Objective

  • Declare double variables for length, width, and perimeter.
  • Prompt the user to enter the length and the width.
  • Calculate the perimeter using the formula: 2 * (length + width).
  • Display the final result clearly to the user.

C++ Solution

rectangle_perimeter.cpp C++ Beginners
#include <iostream>
using namespace std;

int main() {
    double length, width, perimeter;

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

    cout << "Enter the width of the rectangle: ";
    cin >> width;

    // Perimeter formula: P = 2 * (L + W)
    perimeter = 2 * (length + width);

    cout << "The perimeter of the rectangle is: " << perimeter << endl;

    return 0;
}

Console Output:

Enter the length of the rectangle: 10
Enter the width of the rectangle: 5
The perimeter of the rectangle is: 30
Geometric Logic & Operator Precedence
Operator Precedence Multiple Input Handling Geometric Algorithms Floating-Point Arithmetic Variable Management Beginner Math Projects

Share this C++ Exercise

Help others learn geometric calculations in C++.

© C++ Programming Exercises. Master the art of performance coding.