Group
Introduction to C++
Objective
1. Declare two floating-point variables to store the length and width of the rectangle.
2. Ask the user to input the length and width.
3. Use the formula: perimeter = 2 * (length + width) to compute the perimeter.
4. Display the perimeter result with a clear message.
Calculate the perimeter of a rectangle.
Example C++ Exercise
Show C++ Code
#include <iostream> // Include the iostream library for input and output
#include <iomanip> // Include iomanip for formatting output precision
using namespace std; // Use the standard namespace
// Main function - program entry point
int main() {
double length, width, perimeter; // Declare variables for length, width, and perimeter
// Prompt the user to enter the length of the rectangle
cout << "Enter the length of the rectangle: ";
cin >> length; // Read the length from user input
// Prompt the user to enter the width of the rectangle
cout << "Enter the width of the rectangle: ";
cin >> width; // Read the width from user input
// Calculate the perimeter using the formula: 2 * (length + width)
perimeter = 2 * (length + width);
// Set output precision to 2 decimal places and display the result
cout << fixed << setprecision(2);
cout << "The perimeter of the rectangle is: " << perimeter << endl;
return 0; // Return 0 to indicate successful execution
}
Output
Enter the length of the rectangle: 8
Enter the width of the rectangle: 4
The perimeter of the rectangle is: 24.00