C program to print digits of a number in words without using if-else and switch case

  • Write a program in C to print digits of a number in words without using any conditional statement.
  • How to print digits of a number in words.

For Example:
Input : 3546
Output : THREE FIVE FOUR SIX
Algorithm to print digits of a number in words.
  • Create an array of strings(lets call it "words[]"), which will store the mapping of numerical digits to their string value.
  • Take an integer as input from user using scanf function and then convert it to string ssing itoa function.
  • Now, using for loop iterate from first character of string till '\0' character and print their corresponding string values from array of strings("words[]") mapping.

C program to print digits of a number in words without using if-else and switch statement

#include<stdio.h>
#include<stdlib.h>

int main() {
    int num, i;
    char str[20];
    char *words[10] = {"ZERO", "ONE", "TWO", "THREE", "FOUR",
                   "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"};
    
    printf("Enter an integer\n");
    scanf("%d", &num);
    
    itoa(num, str, 10);
    
    for(i=0; str[i] != '\0'; i++)
        printf("%s ", words[str[i] - '0']);
    
    return 0;
}
Output
Enter an integer
2304
TWO THREE ZERO FOUR