C++: Overloaded area()

Write three functions with the same name, area: one for a square (int side), one for a rectangle (int w, int h) and one for a circle (double r, area = 3.14159 × r × r). Then answer each command with the right version.

What to build

Three overloaded area functions, chosen by their arguments.

Requirements

  • Write area(int side), area(int w, int h) and area(double r).
  • Call the right one for each command.
  • Print each area with cout << and no special formatting.

Input

The first line has q (1 ≤ q ≤ 100). Each of the next q lines is square s, rect w h (whole numbers) or circle r (a decimal number).

Output

One line per command: the area, printed with cout << (no special formatting).

Constraints

1 ≤ q ≤ 100.

Example

Input:

3
square 4
rect 2 7
circle 1

Output:

16
14
3.14159

Why it works

The compiler picks an overload from the number and types of the arguments, so one name serves all three shapes.

Examples

Example 1 · Input
3
square 4
rect 2 7
circle 1
Expected output
16
14
3.14159
Example 2 · Input
1
circle 2.5
Expected output
19.6349

Hints

Hint 1

Write three functions named area: area(int side), area(int w, int h) and area(double r).

Hint 2

The call area(s) with an int picks the square version; area(r) with a double picks the circle.

Hint 3

Use 3.14159 for pi.

Solution

Show one correct solution (try it yourself first)
#include <iostream>
#include <string>
using namespace std;

int area(int side) { return side * side; }
int area(int w, int h) { return w * h; }
double area(double r) { return 3.14159 * r * r; }

int main() {
    int q;
    cin >> q;
    for (int i = 0; i < q; i++) {
        string shape;
        cin >> shape;
        if (shape == "square") {
            int s;
            cin >> s;
            cout << area(s) << endl;
        } else if (shape == "rect") {
            int w, h;
            cin >> w >> h;
            cout << area(w, h) << endl;
        } else {
            double r;
            cin >> r;
            cout << area(r) << endl;
        }
    }
    return 0;
}

Lesson: References, overloading and default arguments →