Question:
Write a C++ program to implement a class Rectangle
that represents a rectangle. The class should have private data members length
and width
, and public member functions to set the length and width, calculate the area, calculate the perimeter, and display the details of the rectangle.
Your program should provide a menu-driven interface that allows the user to perform the following actions:
Example:
Menu:
1. Set Length and Width
2. Calculate Area
3. Calculate Perimeter
4. Display Rectangle Details
5. Exit
Enter your choice: 1
Enter length: 5
Enter width: 3
Menu:
1. Set Length and Width
2. Calculate Area
3. Calculate Perimeter
4. Display Rectangle Details
5. Exit
Enter your choice: 2
Area of the rectangle: 15
Menu:
1. Set Length and Width
2. Calculate Area
3. Calculate Perimeter
4. Display Rectangle Details
5. Exit
Enter your choice: 3
Perimeter of the rectangle: 16
Menu:
1. Set Length and Width
2. Calculate Area
3. Calculate Perimeter
4. Display Rectangle Details
5. Exit
Enter your choice: 4
Rectangle Details:
Length: 5
Width: 3
Area: 15
Perimeter: 16
Menu:
1. Set Length and Width
2. Calculate Area
3. Calculate Perimeter
4. Display Rectangle Details
5. Exit
Enter your choice: 5
Exiting the program.
In this question, you'll need to design and implement the Rectangle
class with appropriate member functions and data members. The program should provide a menu to interact with the user and perform the desired actions accordingly.
#include <iostream>
#include <string>
using namespace std;
void menuList();
int main() {
int menu;
int l, w;
int area, perimeter;
menuList();
cout << "Enter your choice: ";
cin >> menu;
while (menu <= 5) {
switch (menu) {
case 1:
cout << "Enter the length: ";
cin >> l;
cout << "Enter the width: ";
cin >> w;
area = l * w;
perimeter = 2 * (l + w);
break;
case 2:
cout << "Area of the rectangle: " << area << '\\n';
break;
case 3:
cout << "Perimeter of the rectangle: " << perimeter << '\\n';
break;
case 4:
cout << "Rectangle Details:\\n";
cout << "Length: " << l << "\\n";
cout << "Width: " << w << "\\n";
cout << "Area: " << area << '\\n';
cout << "Perimeter: " << perimeter << '\\n';
break;
case 5:
cout << "Thank You\\n";
return 0;
break;
default:
cout << "Invalid choice\\n";
break;
}
cout << "Enter your choice: ";
cin >> menu;
}
return 0;
}
void menuList() {
string menu[5] = {"Set Length and Width", "Calculate Area", "Calculate Perimeter", "Display Rectangle Details", "Exit"};
for (int i = 0; i < 5; i++) {
cout << i + 1 << ". " << menu[i] << "\\n";
}
}