Last digit
Use the remainder operator. An easy embedded C problem (Variables and operators), run and graded in the browser.
easy · Variables and operators · remainder
The % operator gives the remainder of a division. 17 % 5 is 2, because 17 is three fives with 2 left over.
Return the last decimal digit of n. n is never negative.
Starter code
int last_digit(int n) {
return 0;
}Example tests
A four-digit number
printf("%d\n", last_digit(1234));Expected output:
4A single digit
printf("%d\n", last_digit(7));Expected output:
7Learn it first
- Variables and operators · Storing values, doing arithmetic, comparing, and the two surprises of integer maths.
More Variables and operators problems
- Average of three · Add three values and divide.
- Celsius to Fahrenheit · Fix a formula that divides too early.
- Time in seconds · Combine several values into one total.
- Even or odd · Produce a yes-or-no answer as 1 or 0.
- Operator precedence · Fix an expression that is evaluated in the wrong order.
- Percentage · Keep precision by ordering the operations correctly.
- Does it fit in a byte? · Combine two comparisons with a logical operator.