basics · beginner · ~10 min

Three-way classify using ternary

Use `?:` for compact conditional expressions.

Challenge

Implement int sign(int n) returning -1 if n < 0, 0 if n == 0, 1 if n > 0. Use the ternary operator ?:.

Why this matters

A nested ternary is the cleanest way to express a 3-way decision; recognising when it improves readability vs hurts it is a real skill.

Input format

signed int.

Output format

-1 / 0 / 1.

Constraints

One line.

Starter code

int sign(int n) { /* TODO */ return 0; }

Common mistakes

Returning n / abs(n) — undefined for n == 0.

Edge cases to handle

0, INT_MAX, INT_MIN.

Complexity

O(1).

Background lessons

Up next

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