basics · beginner · ~15 min

Absolute value

Practise simple branching while handling boundary values.

Challenge

Compute the absolute value of an integer using a conditional.

Task

Implement int my_abs(int n) that returns the absolute value of n: n itself when n is non-negative, and -n when n is negative.

Input

A single int n.

Output

Returns the magnitude of n as an int (always >= 0 for the tested inputs).

Example

my_abs(0)     ->   0
my_abs(5)     ->   5
my_abs(-7)    ->   7
my_abs(-1000) ->   1000

Edge cases

  • n == 0 returns 0.
  • INT_MIN has no positive counterpart in int — the grader does not test it, so you may ignore that overflow case.

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.

Input format

A single int n.

Output format

The absolute value of n, as an int.

Constraints

INT_MIN is not tested; no need to handle its overflow.

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.