user2409559 user2409559 - 2 months ago 17
C Question

Converting two digit number to words using switch statement

The question says to write a program asking the user to enter 2 digit number, then prints the English word for it. Suppose you enter '41' the printf function prints out 'forty one'. I have almost completed the program but stuck on converting 11-19 digits into their corresponding words. I used one switch statement to print the first digit and second switch statement to print the second digit. Have a look at the code:

#include <stdio.h>

int main(void)
{
int first_digit, second_digit;

printf("Enter two digits: ");
scanf("%1d%1d",&first_digit,&second_digit);

switch(first_digit % 10) {
case 1: printf("ten"); break;
case 2: printf("twenty"); break;
case 3: printf("thirty"); break;
case 4: printf("forty"); break;
case 5: printf("fifty"); break;
case 6: printf("sixty"); break;
case 7: printf("seventy"); break;
case 8: printf("eighty"); break;
case 9: printf("ninety"); break;
}
switch(second_digit % 10) {
case 0: break;
case 1: printf(" one"); break;
case 2: printf(" two"); break;
case 3: printf(" three"); break;
case 4: printf(" four"); break;
case 5: printf(" five"); break;
case 6: printf(" six"); break;
case 7: printf(" seven"); break;
case 8: printf(" eight"); break;
case 9: printf(" nine"); break;
}
return 0;
}

Answer

Quick and Dirty

#include <stdio.h>

int main(void)
{
    int first_digit, second_digit;

    printf("Enter two digits: ");
    scanf("%1d%1d",&first_digit,&second_digit);

    if (first_digit == 1) {
        switch(second_digit % 10) {
            case 0: printf(" ten"); break;
            case 1: printf(" eleven"); break;
            case 2: printf(" twelve"); break;
            case 3: printf(" thirteen"); break;
            case 4: printf(" fourteen"); break;
            case 5: printf(" fifteen"); break;
            case 6: printf(" sixteen"); break;
            case 7: printf(" seventeen"); break;
            case 8: printf(" eighteen"); break;
            case 9: printf(" ninteen"); break;
        }
        return 0;
    }
    switch(first_digit % 10) {
        case 1: printf("ten"); break;
        case 2: printf("twenty"); break;
        case 3: printf("thirty"); break;
        case 4: printf("forty"); break;
        case 5: printf("fifty"); break;
        case 6: printf("sixty"); break;
        case 7: printf("seventy"); break;
        case 8: printf("eighty"); break;
        case 9: printf("ninety"); break;
    }
    switch(second_digit % 10) {
        case 0: break;
        case 1: printf(" one"); break;
        case 2: printf(" two"); break;
        case 3: printf(" three"); break;
        case 4: printf(" four"); break;
        case 5: printf(" five"); break;
        case 6: printf(" six"); break;
        case 7: printf(" seven"); break;
        case 8: printf(" eight"); break;
        case 9: printf(" nine"); break;
    }
    return 0;
}
Comments