C++ Area of a Rectangle
#include <iostream>
using namespace std;
// Function to calculate the area of a rectangle
float calculateArea(float length, float width) {
float area = length * width;
return area;
}
int main() {
float length, width, area;
// Input length and width of the rectangle
cout << "Enter length of the rectangle: ";
cin >> length;
cout << "Enter width of the rectangle: ";
cin >> width;
// Calculate the area by calling the function
area = calculateArea(length, width);
// Display the calculated area
cout << "Area of the rectangle is: " << area;
return 0;
}
Explanation:
#include <iostream>
: Includes the input/output stream library to enable standard input and output operations.using namespace std;
: Allows the usage of names for objects and variables from the standard C++ library.float calculateArea(float length, float width) { ... }
: Defines a function namedcalculateArea
that takes the length and width of a rectangle as parameters and returns the calculated area.float area = length * width; return area;
: Calculates the area of the rectangle by multiplying its length and width, then returns the result.int main() { ... }
: Defines the main function where the program's execution begins.float length, width, area;
: Declares variableslength
,width
, andarea
to store user input and the calculated area.cout << "Enter length of the rectangle: ";
: Displays a message prompting the user to enter the length of the rectangle.cin >> length;
: Reads the user input for the length of the rectangle.cout << "Enter width of the rectangle: ";
: Displays a message prompting the user to enter the width of the rectangle.cin >> width;
: Reads the user input for the width of the rectangle.area = calculateArea(length, width);
: Calls thecalculateArea
function with the provided length and width values and stores the returned area in thearea
variable.cout << "Area of the rectangle is: " << area;
: Displays the calculated area of the rectangle to the user.