[Solved] Printing numbers as words


The extra zero is coming from here:

while(o<=i)

i is the number of digits. Since o starts at 0 it ranges from 0 to i, so you go through the loop one extra time. At that point, c is 0, so that’s what gets printed.

You can fix this by changing your condition:

while(o<i)

There is another issue, however. This program prints the words in the reverse order. You can fix this by saving the digits in an array, then looping backward through that array to print the digits.

#include<stdio.h>
int main()
{
    int i=0,a,p;
    int digits[25];  // enough for a 64-bit number
    // list of digits names that can be indexed easily
    char *numberStr[] = { " zero ", " one ", " two ", " three ", " four ", 
                          " five ", " six ", " seven ", " eight ", " nine " };

    printf("enter the number you want ");

    scanf("%d",&a);

    while(a !=0)
    {
        // save each digit in the array
        digits[i] = a%10;
        a=a/10;
        i++;
    }
    i--;   // back off i to contain the index of the highest order digit

    // loop through the array in reverse
    while(i>=0)
    {
        p=digits[i];
        printf("%s", numberStr[i]);
        i--;
    }

    return 0;
}

1

solved Printing numbers as words