I am solving a problem in which a positive integer is given and i have to display it in words.
For example if a number is 2134
the output should be "two one three four"
.
If i use the modulus operator and use the recursion technique, i get the digits starting from the least significant digit i.e "four three one two"
I can also reverse the number and then use modulus operator but i am looking for a better method.
What can be a better approach of solving this problem?.What concept am i missing?
My simple answer:
void printNum(int x)
{
static const char * const num[] = {
"zero ", "one ", "two " , "three ", "four ",
"five ", "six ", "seven ", "eight ", "nine "
};
if (x < 10) {
printf(num[x]);
return;
}
printNum(x / 10);
printNum(x % 10);
}
edit
After some more experimenting and tweaking, I came up with this version. I think this is the about the most "pure" recursive function I can make.
void printNum(int x)
{
static const char * const num[] = {"zero ", "one ", "two ", "three ",
"four ", "five ", "six ", "seven ",
"eight ", "nine "};
(x < 10)? printf(num[x]) : (printNum(x / 10), printNum(x % 10));
}
In case you're looking for recursive solution:
void num2word(int n) {
if (n / 10 == 0) {
// print the word for n
}
else {
num2word(n / 10);
// print the word for n % 10
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With