What is Digit Extraction Loops in C- C Programming Course For Engineering Students

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

PREV_LEC | NEXT_LEC

Digit Extraction Loops in C

Lecture 6 of our free C programming course. Peel a number apart with modulo and division to compute digit sums, products and reversals, the same technique embedded C programming uses for displays and number parsing.

Digit extraction in C is the skill of splitting an integer into its decimal digits using just two operators, the remainder operator % and integer division /. It looks like a classroom puzzle, but the same loop shows up in firmware whenever you must print a sensor value on a seven-segment display, format a number into a UART string without printf, or validate a numeric PIN. This free C tutorial lecture uses the while loop from the previous lesson to build the technique step by step, with original programs you can compile and run today.

What You Will Learn

  • How % 10 isolates the last digit and / 10 removes it.
  • How to write a digit extraction loop and trace it by hand.
  • How to compute the sum, product, count and reverse of the digits of a number.
  • Why accumulators start at 0 for sums and 1 for products.
  • Where this loop is used in embedded C programming.
  • Edge cases such as zero, overflow and negative input.

Prerequisites

You should know the while loop (previous lecture), the arithmetic operators, and the idea of integer division discarding the fractional part. Everything here builds on that, so no extra tools are needed beyond GCC. This lecture belongs to our free embedded C course, so every example keeps the sizes of types in mind.

The Two Operators Behind Digit Extraction

Our number system is base ten. Dividing an integer by ten shifts every digit one place to the right, and the digit that falls off the end is exactly the remainder. C gives you both halves with one operator each.

ExpressionMeaningResult for 4096
n % 10Remainder after dividing by ten, the last digit6
n / 10Integer quotient, the number without its last digit409
n % 100Last two digits96
n / 1000Leading digit of a four-digit number4

Repeat “take the remainder, then divide” until the number reaches zero and you have visited every digit from right to left. The loop condition is simply while (work > 0), because a number with no digits left is zero.

Peeling digits from 90210, right to left

work = 90210digit 0
work = 9021digit 1
work = 902digit 2
work = 90digit 0
work = 9digit 9
work = 0stop, condition false

Example 1: Sum of Digits

We keep the original value in value and destroy a copy called work. That habit matters: the loop consumes its counter, so if you want to print the original at the end you must save it first.

#include <stdio.h>

int main(void)
{
    unsigned int value = 90210;
    unsigned int work = value;
    unsigned int total = 0;

    while (work > 0) {
        unsigned int digit = work % 10;
        printf("digit=%u  left=%u\n", digit, work / 10);
        total += digit;
        work /= 10;
    }
    printf("Digit sum of %u is %u\n", value, total);
    return 0;
}
gcc -Wall -Wextra -std=c11 digsum.c -o digsum
./digsum
digit=0  left=9021
digit=1  left=902
digit=2  left=90
digit=0  left=9
digit=9  left=0
Digit sum of 90210 is 12

Trace table for the digit sum of 90210

Stepwork beforedigittotal afterwork after
Start90210–090210
190210009021
2902111902
39022390
490039
599120

Why does total start at 0? Zero is the identity for addition: adding it changes nothing. If you forget to initialise it, the variable holds whatever happened to be in that memory location, and your answer is garbage plus the digit sum.

Example 2: Product of Digits

For a product the identity is 1, not 0. A starting value of zero would make every product zero. This program also shows a loop inside a loop: the outer one walks a small array of test numbers, the inner one extracts digits.

#include <stdio.h>

int main(void)
{
    unsigned int tests[] = {7342, 5081};
    int i = 0;

    while (i < 2) {
        unsigned int work = tests[i];
        unsigned long product = 1;

        while (work > 0) {
            product *= work % 10;
            work /= 10;
        }
        printf("Digit product of %u is %lu\n", tests[i], product);
        i++;
    }
    return 0;
}
Digit product of 7342 is 168
Digit product of 5081 is 0

7 x 3 x 4 x 2 equals 168. The second number contains a zero digit, and one zero anywhere wipes out the entire product. That is correct arithmetic, not a bug, but worth noting when you design a checksum that multiplies digits.

Example 3: Count and Reverse the Digits

Reversing needs a different update. Each time we pull a digit off the right of the input we push it onto the right of the result, which means shifting the result left by multiplying by ten first. The same loop also counts how many digits there were.

#include <stdio.h>

int main(void)
{
    unsigned int num;
    unsigned int reversed = 0;
    unsigned int count = 0;

    printf("Enter a number: ");
    if (scanf("%u", &num) != 1)
        return 1;

    unsigned int work = num;
    while (work > 0) {
        reversed = reversed * 10 + work % 10;
        work /= 10;
        count++;
    }
    printf("%u has %u digits, reversed it is %u\n", num, count, reversed);
    return 0;
}
gcc -Wall -Wextra -std=c11 reverse.c -o reverse
./reverse
Enter a number: 4096
4096 has 4 digits, reversed it is 6904

Building the reversed number for 4096

Iterationworklast digitreversed after
1409666
2409969
3400690
4446904

Notice what happens with 4090: the reversed value would be 0904, but an integer cannot keep a leading zero, so it prints 904. If the exact digit string matters, store the digits in an array or a character buffer instead.

Digit Extraction in Embedded C Programming

Real boards rarely have a full console. A seven-segment display takes one digit at a time, so a driver extracts digits with exactly this loop and looks each one up in a table of segment patterns. A bootloader without printf may convert a version number into ASCII by adding '0' to each digit. A keypad routine may build a number from typed digits using the opposite step, value = value * 10 + digit, which you just saw in the reverse program.

TaskDigit technique
Show a temperature on a displayExtract digits with % 10, map each to a segment pattern
Print a counter over UART without printfExtract digits, add ‘0’ to each, send in reverse order
Read a PIN from a keypadAccumulate with value = value * 10 + digit
Simple checksum of an ID numberSum or weighted sum of digits

Edge Cases and Common Mistakes

  • Zero input. For 0 the condition work > 0 is false immediately, so the loop reports zero digits even though the number 0 has one. Handle it separately, or use the do-while loop covered in the last lecture of this set.
  • Negative numbers. The remainder of a negative value is negative in modern C, and a loop with work > 0 skips it entirely. Convert to a positive value first, and remember that the most negative integer has no positive twin.
  • Overflow. Products and reversed numbers grow quickly. Reversing 4294967295 does not fit in 32 bits. Pick a wide enough type or check before multiplying.
  • Destroying the original. Work on a copy when you still need the number afterwards.
  • Wrong initial value. Sum starts at 0, product starts at 1, reversed starts at 0.
  • Printing in the wrong order. Digits come out right to left. To print them left to right store them in an array and walk it backwards.
Warning: do not mix signed and unsigned operands without thinking. Using unsigned int in these examples avoids surprises from negative remainders and keeps the arithmetic well defined on small embedded targets.

Best Practices and Performance

  • Division and remainder can be slow on small microcontrollers that have no hardware divider. If you extract digits in a time-critical interrupt, precompute or use the lookup approach offered by your toolchain.
  • Many compilers merge % 10 and / 10 into a single division when they appear together, so writing both next to each other costs little.
  • Prefer fixed-width types such as uint32_t in firmware so the number of digits you can handle is the same on every platform.
  • Validate user input before the loop. A scanf that fails should not leave the program working with an uninitialised value, as the example above checks.

Summary and Key Takeaways

Key takeaways

  • Use % 10 to read the last digit and / 10 to drop it.
  • The loop condition for digit extraction is work > 0.
  • Initialise a sum with 0 and a product with 1.
  • Reverse a number with reversed = reversed * 10 + digit.
  • Zero, negative numbers and overflow are the edge cases to test.

Conclusion

Digit extraction turns two small operators into a surprisingly powerful tool. You have summed, multiplied, counted and reversed digits, traced each loop by hand, and seen where the same pattern appears in embedded C programming. Tracing by hand is the real skill here: whenever a loop surprises you, write a table with one column per variable and one row per iteration. The next lecture of this free embedded C course applies the same style of thinking to factorials and binary-to-decimal conversion, where choosing the right data type becomes critical.

Frequently Asked Questions

Why does digit extraction in C use modulo 10?

Because our numbers are written in base ten. The remainder after dividing by ten is always the last digit.

Why do the digits come out in reverse order?

The remainder gives the rightmost digit first. Store digits in an array and read it backwards if you need left-to-right order.

Can I extract digits from a float?

Not directly. The remainder operator works only on integers. For a float, convert the integer part and the scaled fractional part separately.

What is the difference between work and the original variable?

work is a disposable copy that the loop shrinks to zero, so the original stays available for printing.

How do I handle a negative number?

Take the absolute value into an unsigned variable first, remember the sign, and apply it when you finish.

How many digits does an unsigned 32-bit number have?

At most ten, since the maximum value is 4294967295.

Continue the Free C Tutorial

Next up: factorials, integer overflow and binary to decimal conversion, all explained for embedded C beginners.

PREV_LEC | NEXT_LEC

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →