Spelling Numbers

I would guess that most beginning programmers can deftly craft a loop that outputs sequential integer values, say from 0 to 100. In fact, this is the type of code I write whenever I learn a new language. I asked myself, “Can I write a loop to output values 0 to 100?” Usually in no time, I’ve constructed such a program. Simple.

Of course, when you code a loop in any language, you generate numeric output. Programming languages naturally output values, offering you a choice of bases: decimal, octal, hexadecimal, and some may even offer binary. Not one that I know of, however, outputs values in English (or whatever your mother tongue may be).

Your task for this month’s Exercise is to code the verbal() function. Its argument is an integer value in the range of 0 to 100. Its return value is a string representing the word(s) for the number input.

For example, if you send the verbal() function the integer value 26, it returns the text “twenty six.”

Here is a code skeleton to get started:

2020_09_01-Exercise-skeleton.c

#include <stdio.h>

/* return string representing integers 0 through 100 */
char *verbal(int n)
{
}

int main()
{
    int x;

    for(x=0; x<=100; x++ )
        printf("%s\n",verbal(x));

    return(0);
}

Complete the verbal() function — and be clever with your solution! Yes, it’s possible to code a string array that lists all output values: zero to one hundred. Don’t do that! True, you must code string values for the digits, but be frugal. After all, in the string output of values from 0 to 100 a lot text is repeated.

Click here to view the output from my solution’s sample run. Click here to view my solution, but please try this Exercise on your own before checking to see what I’ve done.

Leave a Reply