I know this is somewhat similar to the program that converts digits to words using things like "Thousands", "Hundred", etc. However, I'm looking to take an integer of any size (such as 543210) and create an output of "Five Four Three Two One Zero". I'm using a switch statement that I think I understand fully and have working. I am stuck on using some sort of loop to single out each digit of the integer and print its word, then repeat for the next digit, and the next. I am fairly new at all this so any help would be appreciated! Thanks.
Here's what I have so far (Not much, but I'm stuck on where to go with a loop):
#include <stdio.h>
int main(void)
{
int num;
printf("Please enter an integer: \n");
scanf("%d", & num);
while (num==0)
{
switch (num)
{
case (0):
printf("Zero ");
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 ");
case (8):
printf("Eight ");
break;
case (9):
printf("Nine ");
break;
case (10):
printf("Ten ");
break;
}
}
return 0;
}
The easiest way to do this is to consume the digits from the right-hand side using integer division "/" & "%".
Here's some partial code:
int digit;
//start a loop
//if num > 10
digit = num % 10;
num = num / 10;
//else
digit = num;
//break the loop
That will print the numbers from right to left. If you want left to right, you could make a recursive function that if num > 10, calls itself with the parameter of num / 10, and then prints the digit value.
Edit: Here's an example of your recursive function:
void convertToWords (int num){
if (num > 10){
convertToWords(num / 10);
int digit = num % 10;
//your switch statement to print the words goes here
}