🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Digit Programs in C
Four digit-processing programs built from one two-operator trick, with real output and embedded uses.
Digit programs in C are the favourite practice problems of every beginner course and every fresher interview: reverse a number, count how often a digit appears, add the even digits, print a number in words. They look like school arithmetic, but they teach a technique you will reuse in embedded C programming for BCD conversion, seven-segment displays and printing numbers on a chip that has no printf. In this lecture of our free C programming course you will learn the two-operator trick behind all of them, write four complete programs from scratch, and see their real output. No copied listings, only code you can type, compile and understand.
What You Will Learn
- The modulo and division trick that peels digits off an integer
- How to reverse a number and why trailing zeros disappear
- How to count a digit with do-while so that zero is handled correctly
- How to separate even and odd digits and combine them with a sum and a product
- How to print a number as words using an array of digit names
- Where these techniques appear in real embedded firmware
Prerequisites
You need the while and do-while loops, the % and / operators, arrays of strings, and scanf with a return-value check. The earlier lectures in this free C tutorial cover all of these. If you can trace a loop by hand, you are ready for digit programs in C.
The Core Idea Behind Digit Programs in C
Every digit program uses two operations on a non-negative integer n. The expression n % 10 is the remainder after dividing by ten, which is exactly the last digit. The expression n / 10 uses integer division, which throws away the last digit. Repeat the pair until n becomes zero, and you have visited every digit from right to left.
The digit loop
Peeling the number 482571
| Step | n before | n % 10 | n / 10 |
|---|---|---|---|
| 1 | 482571 | 1 | 48257 |
| 2 | 48257 | 7 | 4825 |
| 3 | 4825 | 5 | 482 |
| 4 | 482 | 2 | 48 |
| 5 | 48 | 8 | 4 |
| 6 | 4 | 4 | 0 |
Notice that the digits come out in reverse order, 1, 7, 5, 2, 8, 4. That fact explains why reversing a number is easy and why printing a number in words needs one extra trick.
Rule to remember
Use unsigned types for digit work, and remember that n % 10 and n / 10 behave differently for negative numbers. Handle the sign first and then work on the absolute value.
Program 1: Reverse a Number
To reverse a number, build a second number one digit at a time. Each round multiplies the result by ten to make room, then adds the digit that was just peeled off.
File: reverse.c
#include <stdio.h>
int main(void)
{
unsigned long n, work, reversed = 0;
if (scanf("%lu", &n) != 1)
return 1;
work = n;
while (work > 0) {
reversed = reversed * 10 + work % 10; /* append last digit */
work /= 10; /* drop last digit */
}
printf("%lu reversed = %lu\n", n, reversed);
return 0;
}$ gcc -std=c11 -Wall -Wextra -o reverse reverse.c
$ echo "70540" | ./reverse
70540 reversed = 4507
$ echo "1200" | ./reverse
1200 reversed = 21Reversing 70540
| Round | digit | reversed before | reversed after |
|---|---|---|---|
| 1 | 0 | 0 | 0 |
| 2 | 4 | 0 | 4 |
| 3 | 5 | 4 | 45 |
| 4 | 0 | 45 | 450 |
| 5 | 7 | 450 | 4507 |
The trailing zero of 70540 became a leading zero, and numbers do not keep leading zeros, so the answer is 4507. For 1200 the result is 21. That is not a bug in the algorithm, it is a property of integers. If you need to preserve zeros, treat the input as text or collect the digits in an array.
Warning: the reversed value can be larger than the original. On a 32-bit microcontroller, unsigned long is only 32 bits, so a ten-digit number can overflow. Use unsigned long long or limit the number of digits.
Program 2: Count a Digit in a Number
To find whether a digit occurs in a number, and how many times, compare each peeled digit with the target and count the matches. The loop is a do-while on purpose. A plain while (n > 0) would skip the body when the input is 0, and the program would wrongly say the digit 0 is absent from the number 0.
File: digitcount.c
#include <stdio.h>
int main(void)
{
unsigned long n, work;
int d, count = 0;
if (scanf("%lu %d", &n, &d) != 2 || d < 0 || d > 9) {
puts("usage: <number> <digit 0-9>");
return 1;
}
work = n;
do { /* do-while so that n = 0 works */
if ((int)(work % 10) == d)
count++;
work /= 10;
} while (work > 0);
if (count > 0)
printf("digit %d occurs %d time(s) in %lu\n", d, count, n);
else
printf("digit %d is not present in %lu\n", d, n);
return 0;
}$ gcc -std=c11 -Wall -Wextra -o digitcount digitcount.c
$ echo "1223334444 3" | ./digitcount
digit 3 occurs 3 time(s) in 1223334444
$ echo "5050 0" | ./digitcount
digit 0 occurs 2 time(s) in 5050
$ echo "777 1" | ./digitcount
digit 1 is not present in 777
$ echo "0 0" | ./digitcount
digit 0 occurs 1 time(s) in 0| Input | Meaning | Result explained |
|---|---|---|
| 1223334444 3 | Is 3 in 1223334444? | Three 3s appear, so it prints 3 occurrences |
| 5050 0 | Is 0 in 5050? | Two zeros |
| 777 1 | Is 1 in 777? | No 1, so the not-present message |
| 0 0 | Is 0 in 0? | One occurrence thanks to do-while |
Also look at the input check: scanf must return 2 because we read two values, and the digit must be between 0 and 9. Validating input like this is a habit worth building from day one.
Program 3: Sum of Even Digits and Product of Odd Digits
This is the classic six-digit exercise. For every digit, test digit % 2. Even digits go into a sum; odd digits are multiplied into a product. Two details need care. The product must start at 1, not 0, because multiplying by zero would erase every result. And if the number has no odd digit at all, the product would still show 1, which is misleading, so the program remembers whether it saw an odd digit.
File: evenodd.c
#include <stdio.h>
int main(void)
{
unsigned long n;
unsigned long odd_product = 1;
int even_sum = 0, odd_seen = 0;
if (scanf("%lu", &n) != 1 || n < 100000UL || n > 999999UL) {
puts("need exactly six digits");
return 1;
}
while (n > 0) {
int digit = (int)(n % 10);
if (digit % 2 == 0) {
even_sum += digit;
} else {
odd_product *= (unsigned long)digit;
odd_seen = 1;
}
n /= 10;
}
printf("sum of even digits = %d\n", even_sum);
if (odd_seen)
printf("product of odd digits = %lu\n", odd_product);
else
puts("product of odd digits = none (no odd digit present)");
return 0;
}$ gcc -std=c11 -Wall -Wextra -o evenodd evenodd.c
$ echo "482571" | ./evenodd
sum of even digits = 14
product of odd digits = 35
$ echo "246800" | ./evenodd
sum of even digits = 20
product of odd digits = none (no odd digit present)
$ echo "12345" | ./evenodd
need exactly six digitsDigits of 482571
| Digit | Even or odd | even_sum | odd_product |
|---|---|---|---|
| 1 | odd | 0 | 1 |
| 7 | odd | 0 | 7 |
| 5 | odd | 0 | 35 |
| 2 | even | 2 | 35 |
| 8 | even | 10 | 35 |
| 4 | even | 14 | 35 |
The final answers are 14 and 35. The second run, 246800, contains only even digits, so the program reports that there is no odd digit instead of printing a misleading 1. The third input, 12345, has only five digits and is rejected by the range check.
Program 4: Print a Number in Words
Printing 1265 as “one two six five” needs the digits in left-to-right order, but our trick produces them right to left. The solution is to store the digits in an array as they come out and then print the array backwards. A table of names indexed by digit value does the conversion, so there is no long chain of if statements.
File: words.c
#include <stdio.h>
static const char *name[] = {
"zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine"
};
int main(void)
{
unsigned long n;
int digits[6];
int count = 0, k;
if (scanf("%lu", &n) != 1 || n > 999999UL) {
puts("enter a number from 0 to 999999");
return 1;
}
do { /* digits come out last-first */
digits[count++] = (int)(n % 10);
n /= 10;
} while (n > 0);
for (k = count - 1; k >= 0; k--) /* print them first-last */
printf("%s%c", name[digits[k]], k ? ' ' : '\n');
return 0;
}$ gcc -std=c11 -Wall -Wextra -o words words.c
$ echo "1265" | ./words
one two six five
$ echo "4070" | ./words
four zero seven zero
$ echo "0" | ./words
zero
$ echo "1234567" | ./words
enter a number from 0 to 999999Look at the output for 4070. The zeros are printed as “zero”, because the loop treats every digit equally. The input 0 also works, thanks to the do-while that runs at least once. The array has room for six digits, which is why the program rejects anything above 999999 before it starts, protecting the buffer from overflow.
The print loop uses one small idiom, k ? ' ' : '\n', to print a space after every word except the last one, where it prints a newline. It is a compact way to avoid a trailing space.
Where Digit Programs in C Appear in Embedded Work
| Technique | Embedded use |
|---|---|
| Peeling digits with % and / | Converting a sensor value to decimal characters for an LCD, without a heavy printf |
| Storing digits then printing backwards | Writing your own integer-to-string function for a UART logger |
| Digit lookup table | Mapping each digit to the segment pattern of a seven-segment display |
| Digit sum and counts | Simple checksums and check-digit validation of identifiers |
| Packing two digits per byte | BCD values used by real-time clock chips |
That is why interviewers ask for these programs: they check whether you can build a conversion routine from first principles, with limited memory and no library to lean on.
Common Mistakes in Digit Programs in C
| Symptom | Cause | Fix |
|---|---|---|
| Number 0 prints nothing or the wrong result | while loop skips the body when n is 0 | Use do-while |
| Product always 0 | Product started at 0 | Start at 1 |
| Reversed number looks too short | Trailing zeros became leading zeros | Explain or store digits in an array |
| Wrong output for negative input | Remainder of a negative number is negative | Take the absolute value first |
| Garbage output for big input | Overflow of the variable or array | Use a wider type and validate the range |
| Words print in reverse | Digits were printed as peeled | Store them and print backwards |
Best Practices for Digit Programs in C
- Validate before you compute. Check scanf results and the allowed range before using the value.
- Use unsigned types for digit extraction to avoid surprises with negative remainders.
- Performance: division and modulo are slow on cores without a hardware divider, such as a Cortex-M0. If you convert thousands of values, consider fewer divisions or lookup tables.
- Safety: size arrays from the maximum number of digits, and reject inputs that would overflow them.
- Name your tools. Move each program into a small function once you are comfortable, so you can reuse it and test it.
Summary and Key Takeaways
- n % 10 gives the last digit; n / 10 removes it.
- Reversing a number multiplies the result by ten and adds each peeled digit.
- Use do-while so that zero is handled; start products at 1.
- Digits come out right to left, so words need an array and a backwards print.
- These routines appear in real firmware for displays, loggers and BCD data, which is why digit programs in C are asked in interviews.
Conclusion
Digit programs in C may look like beginner exercises, yet they teach the habit of building a result one small step at a time. Practise each program by tracing a different number by hand and then checking it against the compiled version. The next lecture applies the same discipline to number-logic programs such as primes, Fibonacci numbers, Pythagorean triplets and series sums. Continue this free embedded C course in order and type every example yourself.
Frequently Asked Questions
How do I extract the digits of a number in C?
Use n % 10 to get the last digit and n / 10 to remove it. Repeat in a loop until n becomes zero.
Why does reversing 1200 give 21?
The two trailing zeros become leading zeros, and an integer does not store leading zeros. To keep them, store the digits in an array or work with a string.
Why use do-while for digit programs in C?
A do-while runs the body at least once, so the input 0 is processed as one digit instead of being skipped entirely.
How do I print a number in words in C?
Collect digits into an array while peeling them, then print the array from the end to the start, using a table of digit names such as zero to nine.
How do I check a six-digit number?
Test that the value is between 100000 and 999999 inclusive, or count the digits in a loop.
What happens when I take % 10 of a negative number?
In C99 and later the result has the sign of the dividend, so -25 % 10 is -5. Convert to a positive value first to avoid negative digits.
Are digit programs useful in embedded systems?
Yes. They are the basis of integer-to-string conversion, BCD encoding and seven-segment drivers, often needed when no printf is available.
Why are division and modulo slow on some microcontrollers?
Cores such as the Cortex-M0 have no hardware divide instruction, so the compiler calls a software routine. Reduce divisions in hot loops when speed matters.
Keep Going With the Free C Course
This free C tutorial turns beginners into confident embedded C programmers. Continue to the next lecture on primes, Fibonacci numbers and series.

2 Comments