C++: A struct with a function

Group two values in a struct.

What to build

A struct and a function that uses it.

Requirements

  • Define a struct Rect with int members w and h.
  • Write int area(const Rect& r).
  • Read one Rect and print its area.

Input

One line with two whole numbers.

Output

One number.

Constraints

Each number is from 0 to 10000.

Example

Input:

3 4

Output:

12

Why it works

The struct travels as one value, so the function needs only one parameter.

Examples

Example 1 · Input
3 4
Expected output
12
Example 2 · Input
0 5
Expected output
0

Hints

Hint 1

Define the struct above main.

Hint 2

Pass it to the function by const reference.

Solution

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

struct Rect {
    int w;
    int h;
};

int area(const Rect& r) {
    return r.w * r.h;
}

int main() {
    Rect r;
    cin >> r.w >> r.h;
    cout << area(r) << endl;
    return 0;
}

Lesson: Structs and your first class →