Answer to Question #124417 in C++ for Adomako

Question #124417
4. Develop a simple application using functions to calculate the area of the following shapes: Square, Rectangle and Triangle. The user should be able to perform any of the calculation and also press a key to terminate the program
1
Expert's answer
2020-07-01T16:31:02-0400

Let's make several functions, each of which will be responsible for calculating the area of the corresponding figure.

  1. The area of a square is the product of the side of the square on itself.
  2. The area of a rectangle is the product of two sides.
  3. The area of a right triangle is the product of two sides, between which an angle of 90 degrees is divided in half.


In the main function, we implement textual interaction with the user. We will read the commands and respond to them until the user enters the shutdown command.


#include <iostream>
using namespace std;

double calculateSquareArea(double sideLength) {
    return sideLength * sideLength;
}

double calculateRectangleArea(double weight, double height) {
    return weight * height;
}

double calculateTriangleArea(double firstSide, double secondSide) {
    return firstSide * secondSide / 2;
}

int main() {
    string userResponse;
    cout << "Please enter the instructions for what you want to do:" << "\n" <<
         "Square - for calculating area of square by a single side" << "\n" <<
         "Rectangle - for calculating area of rectangle by two sides" << "\n" <<
         "Triangle - for calculating area of right triangle by two sides" << "\n" <<
         "Exit - for closing this application" << "\n";
    cout << "Your command: ";
    while(true) {
        cin >> userResponse;
        if (userResponse == "Square") {
            cout << "Enter a side value: ";
            double side;
            cin >> side;
            cout << "Area of this square is " << calculateSquareArea(side) << "\n";
        } else if (userResponse == "Rectangle") {
            cout << "Enter a two values - width and height of a rectangle: ";
            double width, height;
            cin >> width >> height;
            cout << "Area of this rectangle is " << calculateRectangleArea(width, height) << "\n";
        } else if (userResponse == "Triangle") {
            cout << "Enter a two values - first and second sides of a right triangle: ";
            double firstSide, secondSide;
            cin >> firstSide >> secondSide;
            cout << "Area of this triangle is " << calculateTriangleArea(firstSide, secondSide) << "\n";
        } else if(userResponse == "Exit") {
            return 0;
        }
        cout << "Please write a next command: ";
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS