data-structures · beginner · ~15 min

Rectangle area

Pass a struct by value and use its fields.

Challenge

Compute the area of a rectangle from its width and height.

Task

Define struct Rect { int w, h; }; and implement long rect_area(struct Rect r) that returns the area w * h.

Input

One struct Rect value passed by value, with int fields w (width) and h (height).

Output

The area w * h as a long.

Example

r={3,4}    ->   12
r={10,10}  ->   100
r={0,5}    ->   0

Edge cases

  • A zero width or height gives area 0.
  • Promote to long before multiplying so large dimensions do not overflow.

Input format

One struct Rect value (with int w, h), passed by value.

Output format

long: the area w * h.

Constraints

Cast to long before multiplying to avoid int overflow.

Starter code

struct Rect { int w, h; };

long rect_area(struct Rect r) {
    /* TODO */
    return 0;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.