// Elaine Torrez CS1A Chapter 6, P.369, #2
// *****************************************************************************************
// * RECTANGLE AREA *
// *--------------------------------------------------------------------------------------- *
// * This program asks the user to enter the length and width of a rectangle, then *
// * calculates and displays the rectangle’s area. *
// * The program uses separate functions to get the input values, calculate the area, *
// * and display the results. *
// *--------------------------------------------------------------------------------------- *
// * INPUT *
// * length : Length of the rectangle (must be positive) *
// * width : Width of the rectangle (must be positive) *
// *--------------------------------------------------------------------------------------- *
// * OUTPUT *
// * area : The calculated area of the rectangle *
// *****************************************************************************************
#include <iostream>
#include <iomanip>
#include <limits> // for input validation
using namespace std;
// ---------------- Function Prototypes ----------------
double getLength();
double getWidth();
double getArea(double length, double width);
void displayData(double length, double width, double area);
// ---------------------- MAIN -------------------------
int main()
{
double length, width, area;
// Get length and width using input functions
length = getLength();
width = getWidth();
// Calculate the area
area = getArea(length, width);
// Display results
displayData(length, width, area);
return 0;
}
// ---------------- Function Definitions ----------------
// Function to get the rectangle's length
double getLength()
{
double length;
cout << "Enter the rectangle's length: ";
cin >> length;
// Validate input
while (cin.fail() || length <= 0.0)
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "ERROR: Length must be positive. Re-enter: ";
cin >> length;
}
return length;
}
// Function to get the rectangle's width
double getWidth()
{
double width;
cout << "Enter the rectangle's width: ";
cin >> width;
// Validate input
while (cin.fail() || width <= 0.0)
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "ERROR: Width must be positive. Re-enter: ";
cin >> width;
}
return width;
}
// Function to calculate the rectangle's area
double getArea(double length, double width)
{
return length * width;
}
// Function to display the results
void displayData(double length, double width, double area)
{
cout << fixed << setprecision(2);
cout << "\nLength : " << length << endl;
cout << "Width : " << width << endl;
cout << "Area : " << area << endl;
}