fork download
  1. /*create a program with an area function that is overloaded to calcuilate
  2. the area of a circle (given the radius)
  3. the area of rectangle (given length and width)
  4. the area of triangle (given the three side of the triangle)*/
  5. #include <iostream>
  6. #include <cmath>
  7. using namespace std;
  8.  
  9. #define PI 3.14159
  10.  
  11. // Area of a circle
  12. double area(double radius) {
  13. return PI * radius * radius;
  14. }
  15.  
  16. // Area of a rectangle
  17. double area(double length, double width) {
  18. return length * width;
  19. }
  20.  
  21. // Area of a triangle using Heron's formula
  22. double area(double a, double b, double c) {
  23. double s = (a + b + c) / 2; // semi-perimeter
  24. return sqrt(s * (s - a) * (s - b) * (s - c));
  25. }
  26.  
  27. int main() {
  28. int choice;
  29.  
  30. cout << "Choose the shape to calculate the area:" << endl;
  31. cout << "1. Circle" << endl;
  32. cout << "2. Rectangle" << endl;
  33. cout << "3. Triangle" << endl;
  34. cout << "Enter your choice (1/2/3): ";
  35. cin >> choice;
  36.  
  37. if (choice == 1) {
  38. double radius;
  39. cout << "Enter the radius of the circle: ";
  40. cin >> radius;
  41. cout << "The area of the circle is: " << area(radius) << endl;
  42. }
  43. else if (choice == 2) {
  44. double length, width;
  45. cout << "Enter the length and width of the rectangle: ";
  46. cin >> length >> width;
  47. cout << "The area of the rectangle is: " << area(length, width) << endl;
  48. }
  49. else if (choice == 3) {
  50. double a, b, c;
  51. cout << "Enter the lengths of the three sides of the triangle: ";
  52. cin >> a >> b >> c;
  53.  
  54. // Check if a valid triangle can be formed with the given sides
  55. if (a + b > c && a + c > b && b + c > a) {
  56. cout << "The area of the triangle is: " << area(a, b, c) << endl;
  57. } else {
  58. cout << "Invalid triangle sides!" << endl;
  59. }
  60. } else {
  61. cout << "Invalid choice!" << endl;
  62. }
  63.  
  64. return 0;
  65. }
  66.  
  67.  
  68.  
  69.  
Success #stdin #stdout 0.01s 5320KB
stdin
Standard input is empty
stdout
Choose the shape to calculate the area:
1. Circle
2. Rectangle
3. Triangle
Enter your choice (1/2/3): Invalid choice!