basics · beginner · ~15 min

Absolute value

Practise simple branching while handling boundary values.

Challenge

Implement int my_abs(int n) returning the absolute value of n. Watch out for INT_MIN.

Why this matters

Absolute value is one of the simplest functions you'll write, but it has a famous trap: -INT_MIN doesn't fit in int. Handling that gracefully separates careful programmers from sloppy ones.

Starter code

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

Common mistakes

Returning -n without the < 0 check (the negation has no effect for positive n). Using fabs() (that's for doubles).

Edge cases to handle

0 → 0. INT_MIN — its magnitude exceeds INT_MAX. Skip or widen.

Complexity

O(1).

Background lessons

Up next

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