basics · beginner · ~15 min
Practise simple branching while handling boundary values.
Compute the absolute value of an integer using a conditional.
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.
A single int n.
Returns the magnitude of n as an int (always >= 0 for the tested inputs).
my_abs(0) -> 0
my_abs(5) -> 5
my_abs(-7) -> 7
my_abs(-1000) -> 1000
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.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.
A single int n.
The absolute value of n, as an int.
INT_MIN is not tested; no need to handle its overflow.
int my_abs(int n) { /* TODO */ return 0; }
Returning -n without the < 0 check (the negation has no effect for positive n). Using fabs() (that's for doubles).
0 → 0. INT_MIN — its magnitude exceeds INT_MAX. Skip or widen.
O(1).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.