🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Embedded C Digit Recursion Tricks
Reverse digits and test divisibility by 11 with recursion, and learn what each choice costs in embedded C programming.
In this lecture of our free C course you will learn a skill that sits at the heart of embedded C programming: taking a number apart one digit at a time. Firmware prints sensor values to displays and serial ports, validates serial numbers, and parses text that arrives byte by byte, and all of it rests on two humble operators, remainder and division by ten. You will use recursion to reverse the digits of a number and to test divisibility by 11 with a classic digit rule, and you will see exactly when recursion is a good fit for embedded C programming and when a plain loop is the safer choice.
The two problems look unrelated, yet both are solved by the same move: peel off the last digit, deal with it, and hand the rest of the number to the same function. That is recursion in its cleanest form.
What You Will Learn in This Embedded C Programming Lecture
- How
n % 10andn / 10split a number into its last digit and the rest. - The difference between printing digits in reverse and computing the reversed value, and why leading zeros expose it.
- How the order of a statement relative to the recursive call decides whether digits come out right to left or left to right.
- How an accumulator turns recursion into tail recursion, and what that means for stack usage on a microcontroller.
- Why the alternating digit sum proves divisibility by 11, and how to code it recursively.
- When to prefer a loop or a digit-string method, including a way to test numbers too long for any integer type.
Prerequisites
You should know the base case and recursive case of a recursive function and have seen factorial or Fibonacci written recursively in earlier lectures of this chapter. You also need integer division and the remainder operator, and a basic feeling for the call stack. If those are fuzzy, reread the recursion lectures first; every idea here builds directly on them.
The Digit Extraction Toolkit
Integer division by ten throws away the last decimal digit, and the remainder after division by ten is that last digit. Together they split any non-negative number into two pieces. Repeating the split until nothing is left visits every digit from right to left.
| Current n | n % 10 (last digit) | n / 10 (the rest) |
|---|---|---|
| 4821 | 1 | 482 |
| 482 | 2 | 48 |
| 48 | 8 | 4 |
| 4 | 4 | 0 |
Each step shrinks the problem by one digit, which is precisely what recursion needs: a smaller version of the same problem and a point where it stops.
Problem One: Reversing the Digits
“Reverse a number” hides two different questions. One is “print the digits in reverse order”. The other is “produce a new number whose digits are reversed”. They give the same answer for 12345 but differ for 1200. Printing right to left shows 0021, because the zeros are real digits. The reversed value is 21, because a number cannot store leading zeros. Always decide which behaviour the requirement asks for before you write a line of code.
| Input | Printed in reverse | Reversed value |
|---|---|---|
| 12345 | 54321 | 54321 |
| 1200 | 0021 | 21 |
| 907 | 709 | 709 |
| 0 | 0 | 0 |
Printing Right to Left
The recursive version prints the last digit first and then recurses on the rest. Because the print happens before the call, the digits appear in right-to-left order. The base case is any number below ten, which prints itself and stops; this also makes zero print a single 0 instead of printing nothing.
static void print_digits_reversed(unsigned long n)
{
if (n < 10) {
putchar('0' + (int)n);
return;
}
putchar('0' + (int)(n % 10));
print_digits_reversed(n / 10);
}
Order of statements is behaviour. Move the putchar after the recursive call and the function prints the digits left to right, because output now happens while the calls unwind. The same two lines in a different order give opposite results. The next lecture uses exactly this effect for number base conversion.
Computing the Reversed Value with an Accumulator
To build a number you need somewhere to collect digits. The classic trick is an extra parameter, the accumulator, which carries the partial result down the calls. At each step the accumulator is multiplied by ten and the new last digit is added. When the input reaches zero, the accumulator holds the answer and is simply returned back up the chain.
static unsigned long reverse_value(unsigned long n, unsigned long acc)
{
if (n == 0)
return acc;
return reverse_value(n / 10, acc * 10 + n % 10);
}
| Frame | n | acc | What happens |
|---|---|---|---|
| 1 (outermost) | 1203 | 0 | calls with n = 120, acc = 3 |
| 2 | 120 | 3 | calls with n = 12, acc = 30 |
| 3 | 12 | 30 | calls with n = 1, acc = 302 |
| 4 | 1 | 302 | calls with n = 0, acc = 3021 |
| 5 (innermost) | 0 | 3021 | base case, returns 3021 |
This is tail recursion: the recursive call is the very last thing the function does, with nothing left to do afterwards except return the result. An optimising compiler may turn such a call into a jump and reuse the same frame, but the C standard does not promise it. GCC commonly does this at higher optimisation levels, yet at -O0, which is what you often use while debugging, every call consumes a new frame. Never rely on the optimiser for correctness; count the worst-case depth yourself. For an unsigned 32-bit value that is at most ten digits, so ten frames, and for 64-bit about twenty.
unsigned long is 32 bits wide the accumulator silently wraps. Use a wider type, or detect the overflow before multiplying.Problem Two: Divisibility by 11 with Digits
A pencil rule says a number is divisible by 11 when the sum of its digits in odd positions minus the sum of its digits in even positions is zero or a multiple of 11. The reason is neat. Since 10 is one less than 11, ten raised to any power leaves remainder 1 or -1 when divided by 11, alternating with each position. So every digit contributes either plus itself or minus itself to the remainder, and the whole number behaves like its alternating digit sum.
The recursive plan has two parts. A helper computes the alternating sum starting from the last digit as positive. The main function takes the absolute value of that sum; if it is 11 or more, it applies the test again to that smaller number, otherwise it simply checks for zero.
static long alternating_sum(long n)
{
if (n == 0)
return 0;
return n % 10 - alternating_sum(n / 10);
}
static int divisible_by_11(long n)
{
long d = alternating_sum(n);
if (d < 0)
d = -d;
if (d >= 11)
return divisible_by_11(d);
return d == 0;
}
The subtraction inside alternating_sum does the sign flipping for free: each recursive call is subtracted from the current digit, which makes the next digit negative, the one after positive, and so on. The reduction always terminates because for any number of ten or more the digit sum is strictly smaller than the number itself, so every round shrinks the problem.
| Round | Value tested | Digits, right to left, with signs | Absolute result | Decision |
|---|---|---|---|---|
| 1 | 918082 | +2 -8 +0 -8 +1 -9 | 22 | 22 is 11 or more, test again |
| 2 | 22 | +2 -2 | 0 | zero, so divisible |
Complete Embedded C Programming Example with Real Output
The listing includes both recursive solutions, an iterative twin of the reverse function, a traced version of the divisibility test, an exhaustive comparison against the built-in remainder operator, and a string-based version for numbers too long to store in any integer.
#include <stdio.h>
#include <string.h>
/* prints the digits of n from right to left */
static void print_digits_reversed(unsigned long n)
{
if (n < 10) {
putchar('0' + (int)n);
return;
}
putchar('0' + (int)(n % 10));
print_digits_reversed(n / 10);
}
/* returns the reversed number as a value (accumulator style) */
static unsigned long reverse_value(unsigned long n, unsigned long acc)
{
if (n == 0)
return acc;
return reverse_value(n / 10, acc * 10 + n % 10);
}
/* the same job with a loop: no stack growth at all */
static unsigned long reverse_loop(unsigned long n)
{
unsigned long acc = 0;
while (n != 0) {
acc = acc * 10 + n % 10;
n /= 10;
}
return acc;
}
/* d0 - d1 + d2 - d3 ... counting from the rightmost digit */
static long alternating_sum(long n)
{
if (n == 0)
return 0;
return n % 10 - alternating_sum(n / 10);
}
static int divisible_by_11(long n)
{
long d = alternating_sum(n);
if (d < 0)
d = -d;
if (d >= 11)
return divisible_by_11(d);
return d == 0;
}
static int traced(long n)
{
long d = alternating_sum(n);
if (d < 0)
d = -d;
printf(" value %ld -> |alternating sum| = %ld\n", n, d);
if (d >= 11)
return traced(d);
return d == 0;
}
/* works on a digit string of any length: no integer type can overflow */
static int string_divisible_by_11(const char *digits)
{
long sum = 0;
int sign = 1;
size_t i = strlen(digits);
while (i > 0) {
i--;
sum += sign * (digits[i] - '0');
sign = -sign;
}
if (sum < 0)
sum = -sum;
return sum % 11 == 0;
}
int main(void)
{
static const unsigned long tests[] = {12345UL, 1200UL, 907UL, 0UL, 5UL};
static const long probes[] = {121L, 1331L, 123456L, 918082L, 8091L};
size_t i;
long n;
int mismatches = 0;
puts("-- reversing digits --");
for (i = 0; i < sizeof tests / sizeof tests[0]; i++) {
printf("%6lu printed reversed: ", tests[i]);
print_digits_reversed(tests[i]);
printf(" reversed value: %lu loop: %lu\n",
reverse_value(tests[i], 0), reverse_loop(tests[i]));
}
puts("\n-- divisibility by 11 --");
for (i = 0; i < sizeof probes / sizeof probes[0]; i++)
printf("%7ld %s\n", probes[i], divisible_by_11(probes[i]) ? "divisible" : "not divisible");
puts("\ntrace for 918082:");
printf(" result: %s\n", traced(918082L) ? "divisible" : "not divisible");
for (n = 0; n <= 200000L; n++)
if (divisible_by_11(n) != (n % 11 == 0))
mismatches++;
printf("\ncompared with n %% 11 for 0..200000, mismatches: %d\n", mismatches);
puts("\n-- digit strings too long for any integer --");
printf("98765432123456789012345672 -> %s\n",
string_divisible_by_11("98765432123456789012345672") ? "divisible" : "not divisible");
printf("98765432123456789012345673 -> %s\n",
string_divisible_by_11("98765432123456789012345673") ? "divisible" : "not divisible");
printf("1210000000000000000000000000 -> %s\n",
string_divisible_by_11("1210000000000000000000000000") ? "divisible" : "not divisible");
return 0;
}
gcc -std=c99 -Wall -Wextra -pedantic -o digits digits.c
./digits
Output from a real run:
-- reversing digits --
12345 printed reversed: 54321 reversed value: 54321 loop: 54321
1200 printed reversed: 0021 reversed value: 21 loop: 21
907 printed reversed: 709 reversed value: 709 loop: 709
0 printed reversed: 0 reversed value: 0 loop: 0
5 printed reversed: 5 reversed value: 5 loop: 5
-- divisibility by 11 --
121 divisible
1331 divisible
123456 not divisible
918082 divisible
8091 not divisible
trace for 918082:
value 918082 -> |alternating sum| = 22
value 22 -> |alternating sum| = 0
result: divisible
compared with n % 11 for 0..200000, mismatches: 0
-- digit strings too long for any integer --
98765432123456789012345672 -> divisible
98765432123456789012345673 -> not divisible
1210000000000000000000000000 -> divisible
Look at the 1200 row: the printed form is 0021 while both value-producing versions return 21. The exhaustive check compares the recursive digit rule with n % 11 for every number from 0 to 200000 and finds no disagreement. The last block runs the string version on numbers with 26 and 28 digits, far beyond any integer type, and correctly separates the divisible neighbours from the non-divisible one.
When Recursion Fits Embedded C Programming
Recursion costs stack. Every call stores a return address and saved registers, and on a small microcontroller the stack may be only a few hundred bytes. For digit problems the depth is bounded by the number of digits, which is small and known, so recursion is acceptable here. Even so, many safety standards forbid it outright; for example, MISRA C:2012 includes a rule against functions calling themselves. If your project follows such a standard, use the loop version shown in the listing, which gives identical answers with constant stack usage.
| Question | Recursive version | Loop version |
|---|---|---|
| Stack use | one frame per digit | constant |
| Code clarity for digit order | very clear, order follows statement placement | needs care with accumulators |
| Allowed in strict coding standards | often not | yes |
| Cost of / and % | same | same |
Notice the last row. Both versions divide by ten at every step. On a core without a hardware divider, such as a Cortex-M0, each division becomes a library call, so digit extraction is not free. This is why serious firmware often keeps numbers as text or as binary-coded decimal when it only needs to display them, and why the string version in the listing is attractive: it processes ASCII digits with only additions and subtractions, and it can handle serial numbers or barcodes far longer than any integer register.
Real-World Uses
Reversing digits underlies palindrome checks and converting a number into text for an LCD or UART without a heavy printf. The alternating-sum idea is a cousin of the check digits found on identifiers; the ISBN-10 check, for instance, uses arithmetic modulo 11. A device that receives an identifier as text can validate it on the fly, byte by byte, without ever storing the whole number.
Common Mistakes and Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Zero prints nothing | Base case tests n == 0 and returns without printing | Use n < 10 as the base case so a lone digit prints |
| Digits come out in the wrong order | Print placed before or after the call by mistake | Print before the call for right to left, after for left to right |
| Reversed value is shorter than expected | Leading zeros cannot be stored in a number | Print digits instead, or store them in a string |
| Wrong answer for large inputs | Accumulator overflowed a narrow type | Use a wider unsigned type or check before multiplying |
| Negative numbers misbehave | Remainder of a negative number can be negative | Take the absolute value first, as the wrapper does |
| Stack overflow on the target | Deep recursion on a tiny stack | Bound the depth or use the loop version |
Best Practices, Performance and Security
- Write the base case first and make sure every recursive call moves strictly toward it.
- Name the behaviour you need, printing or computing, before choosing the algorithm.
- Use unsigned types for digit arithmetic so wraparound is defined, and size them for the largest input.
- Test exhaustively over a range against a trusted reference, as the listing does with the remainder operator.
- Performance: each digit costs one division and one remainder; compilers often merge them into one instruction on cores that have a divider.
- Security: never trust digit strings from outside. Validate that every character is between ‘0’ and ‘9’ before subtracting ‘0’, or garbage input will produce garbage arithmetic.
Key Takeaways and Conclusion
Key takeaways
n % 10andn / 10split a number into last digit and remainder, the foundation of digit recursion.- Printing in reverse and computing the reversed value differ whenever the input ends in zeros.
- Statement order around the recursive call decides whether output is right to left or left to right.
- An accumulator makes recursion tail recursive, but the standard does not guarantee frame reuse.
- The alternating digit sum decides divisibility by 11 because ten is congruent to minus one modulo 11.
- For long digit streams or strict standards, a loop or a string method is the better embedded choice.
You solved two classic problems with the same peeling move and then asked the questions an embedded engineer must ask: how deep does the stack go, what happens at the edges of the type, and is there a version that costs less on this particular core? That mindset is the real content of embedded C programming. The next lecture takes the statement-order idea you met here and turns it into a compact recursive routine for printing a number in binary, octal or hexadecimal.
Frequently Asked Questions: Digit Recursion in C
What is the difference between printing digits in reverse and reversing the value?
Printing emits every digit including trailing zeros, so 1200 shows as 0021. A reversed numeric value cannot store leading zeros, so it becomes 21. Decide which behaviour you need before coding.
Is recursion safe in embedded C programming?
It can be when the depth is small and bounded, as with digit problems. Each call uses stack, and some safety standards such as MISRA C:2012 forbid recursion, so a loop is often the safer choice.
Why does the alternating digit sum test divisibility by 11?
Ten is congruent to minus one modulo 11, so powers of ten alternate between 1 and -1. Each digit therefore contributes plus or minus itself to the remainder, and the number behaves like its alternating digit sum.
Why not just use n % 11?
For a value that fits an integer, the remainder operator is simpler and should be preferred. The digit method matters for digit streams or strings too long for any integer type, where it needs only additions and subtractions.
Does C guarantee tail call optimisation?
No. Compilers such as GCC often convert tail calls into jumps when optimising, but the standard does not require it, so never rely on it to prevent stack overflow.
How do I handle negative numbers?
Take the absolute value before extracting digits, because the remainder of a negative number can be negative. The wrapper in the lesson does this for the alternating sum.
Can reversing digits overflow?
Yes. The digits of 4294967295 reversed give 5927694924, which exceeds a 32-bit unsigned type. Use a wider type or check before each multiplication by ten.
Master the Call Stack
Keep learning embedded C programming with the next lecture on converting numbers between bases.

1 Comment