What is Number to Words in C- Free Embedded C Programming Course

🚀 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 →

Free C Programming Course · Strings · Lecture 37

Number to Words in C

Turn 0 to 9999 into English text with lookup tables and a safe string builder. A practical exercise from our free embedded C course.

Converting a number into words, so that 2026 becomes “two thousand twenty six”, is a favourite interview question and a surprisingly good lesson in table-driven design. In this lecture of our free C programming course you will write a number to words converter in C that fills a caller-supplied buffer, checks its limits, and uses two small const tables instead of a thicket of if statements. The same table-driven style is the backbone of embedded C programming: command tables, error-message tables, display-segment tables and more. If you are working through this free C tutorial to become job-ready, take your time with this one.

What You Will Learn

  • How to break a number into thousands, hundreds, tens and ones with / and %
  • How to use arrays of string pointers as lookup tables
  • Why the teens (11 to 19) need special handling
  • How to build output text safely in a fixed buffer
  • How to return an error code instead of printing from inside the function

Prerequisites

You should know arrays of pointers to strings, strlen, strncat, and integer division and remainder. If you need a refresher, revisit the earlier lectures on arrays of strings in this free embedded C course.

Breaking a Number into Parts

English reads numbers in groups. For a value from 0 to 9999 we need only four steps, and each one peels off a part using division and remainder.

Splitting 5021 into spoken parts

5021/ 1000 = 5“five thousand”
021/ 100 = 0skip hundreds
21/ 10 = 2“twenty”
1% 10 = 1“one”
RangeHow it is spokenTable used
0 to 19one unique word eachsmall[]
20 to 99decade word, then ones worddecade[] + small[]
100 to 999ones word, “hundred”, then the restsmall[]
1000 to 9999ones word, “thousand”, then the restsmall[]

Why Teens Are Special

Numbers 11 to 19 are not built from a decade word and a ones word. We say “thirteen”, not “ten three”. The simple fix is to store every word from zero to nineteen in one table, so any value below 20 is a direct lookup. Only from 20 upwards do we combine two words. This single decision removes an entire else if branch compared with code that special-cases the teens separately.

Design: Return Text, Do Not Print It

A function that prints directly is hard to reuse. If you later want the text on an LCD, in a log line, or in a unit test, you would have to rewrite it. A better design fills a buffer supplied by the caller and returns a status code. The caller decides what to do with the text.

  • Input: the number and the buffer with its capacity.
  • Output: 0 on success, -1 if the number is out of range or the buffer is unusable.
  • Safety: the helper never writes past the buffer, because every append is limited by the remaining space.

The Complete Program

#include <stdio.h>
#include <string.h>

static const char *const small[] = {
    "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
    "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
    "sixteen", "seventeen", "eighteen", "nineteen"
};
static const char *const decade[] = {
    "", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy",
    "eighty", "ninety"
};

/* append a word to out, adding a space if out already has text */
static void put_word(char *out, size_t cap, const char *w)
{
    size_t len = strlen(out);
    if (len > 0 && len + 1 < cap)
        out[len++] = ' ', out[len] = '\0';
    strncat(out, w, cap - len - 1);
}

/* converts 0..9999, returns 0 on success, -1 if out of range */
int number_to_words(unsigned n, char *out, size_t cap)
{
    if (n > 9999 || cap == 0)
        return -1;
    out[0] = '\0';
    if (n == 0) {
        put_word(out, cap, small[0]);
        return 0;
    }
    if (n >= 1000) {
        put_word(out, cap, small[n / 1000]);
        put_word(out, cap, "thousand");
        n %= 1000;
    }
    if (n >= 100) {
        put_word(out, cap, small[n / 100]);
        put_word(out, cap, "hundred");
        n %= 100;
    }
    if (n >= 20) {
        put_word(out, cap, decade[n / 10]);
        n %= 10;
        if (n)
            put_word(out, cap, small[n]);
    } else if (n > 0) {
        put_word(out, cap, small[n]);
    }
    return 0;
}

int main(void)
{
    unsigned tests[] = {0, 7, 13, 40, 99, 100, 305, 1000, 2026, 5021, 9999, 12000};
    char buf[80];
    for (size_t i = 0; i < sizeof tests / sizeof tests[0]; i++) {
        if (number_to_words(tests[i], buf, sizeof buf) == 0)
            printf("%5u -> %s\n", tests[i], buf);
        else
            printf("%5u -> out of range\n", tests[i]);
    }
    return 0;
}

Build and Run

$ gcc -std=c11 -Wall -Wextra -o words words.c
$ ./words

Expected Output

    0 -> zero
    7 -> seven
   13 -> thirteen
   40 -> forty
   99 -> ninety nine
  100 -> one hundred
  305 -> three hundred five
 1000 -> one thousand
 2026 -> two thousand twenty six
 5021 -> five thousand twenty one
 9999 -> nine thousand nine hundred ninety nine
12000 -> out of range

Walking Through the Code

The Lookup Tables

Both tables are static const char *const. The inner const protects the pointer slots themselves, the other protects the text, so the whole table can live in flash on a microcontroller instead of being copied into RAM. That is a real saving on small devices. The two empty strings at the start of decade[] exist so the index equals the tens digit: decade[2] is “twenty”.

The Safe Word Appender

put_word is the only function that touches the output buffer. It adds a space when the buffer already has text, then uses strncat with the remaining capacity so it can never write beyond cap. If the buffer is too small, the text is cut rather than corrupting memory. Keeping all writes in one small helper makes the safety easy to audit.

The Peeling Logic

The body is four stages. Each stage handles one magnitude, then reduces n with %= so the next stage sees only what is left. Because zero is handled up front, the later stages never print “zero” by accident, which is why 1000 prints “one thousand” and not “one thousand zero”.

Design Note

Notice there is no switch and no long chain of if statements for individual numbers. Data lives in tables and the code stays short. Adding another language means swapping the tables, not rewriting the logic.

Extending the Converter

GoalWhat to change
Support up to 999999Split into groups of three digits and reuse a three-digit helper twice
Add “and” (British style)Insert “and” before the tens part when a hundreds part exists
Ordinals (first, second)Use a second table of ordinal words for the last part
Hyphens (twenty-six)Change the separator before the ones word
Another languageReplace the tables and adjust the grammar rules

Real-World Uses

  • Voice and audio prompts: a device that speaks a reading by joining pre-recorded word clips needs exactly this word sequence.
  • Cheque and invoice printing: amounts in words are required on many financial documents.
  • Accessibility: screen readers and talking meters turn numbers into speech.
  • Display drivers: character LCDs sometimes show short word labels from a table.

Common Mistakes

  • Printing from inside the function so the result cannot be reused or tested.
  • Forgetting the range check. An index of 10000 / 1000 = 10 would still be valid here, but 20000 would read past the end of small[].
  • Using a signed int and letting a negative value slip into an array index.
  • Handling zero inside the later stages, which produces odd output such as “one hundred zero”.
  • Unsafe appending with strcat and no capacity check.

Best Practices

  • Return an error code and let the caller choose how to report it.
  • Keep every buffer write in a single, well-tested helper.
  • Make tables const so they can stay in flash.
  • Test the edges: 0, 19, 20, 99, 100, 1000, 9999 and one value out of range.

Suggested Images

Image ideaSuggested ALT text
Diagram splitting a number into thousands, hundreds, tens, onesnumber to words converter in C, free C programming course diagram
Two lookup tables side by sidelookup table in embedded C programming, free C tutorial
Terminal showing the program outputC program converting numbers to words, free embedded C course

Summary and Key Takeaways

  • Division and remainder split a number into spoken groups.
  • One table for 0 to 19 and one for the tens remove the special cases.
  • Fill a caller-supplied buffer and return a status instead of printing.
  • One bounded append helper keeps the buffer safe.
  • Table-driven code is short, testable and flash-friendly in embedded C programming.

Conclusion

You have built a clean number to words converter in C and, more importantly, practised the habits that matter in firmware: tables over branching, bounded writes, and functions that return data instead of printing it. In the next lecture of this free C programming course we go the other way and convert text back into a number safely.

Frequently Asked Questions

Why store 0 to 19 in one table?

Because the teens have unique names. A single table makes every value below 20 a direct lookup.

Why return an int instead of printing?

Returning a status and filling a buffer makes the function reusable for displays, logs and tests.

What does static const char *const mean?

The array holds constant pointers to constant text, so the compiler can place the table in read-only memory such as flash.

How can I support larger numbers?

Process the number in groups of three digits and reuse the same three-digit routine, adding words such as thousand and million.

Is strncat safe here?

It is safe when you pass the remaining space correctly, as put_word does. Plain strcat gives no such protection.

Can the tables be translated to other languages?

Yes, but grammar differs by language, so you may need to change the logic as well as the words.

Keep Learning with the Free C Programming Course

Table-driven design is everywhere in firmware. Continue to the next lecture in this free embedded C course.

💬 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 →