Convert Digits to Strings

Learn to use Recursion to solve coding problems.

We'll cover the following...

Problem statement

*Given a number n, convert each digit of that number to its corresponding string. Make sure the order is correct.

For example, let us take n = 278. The output should be two seven eight.

Solution: Recursive approach

The problem looks very easy and it could have been implemented without using Recursion. But to understand the concept of Recursion, it is very important that we discuss some basic problems too.

Let us first visualize how Recursion might help in solving this problem.

Let us now move to the implementation.

Press + to interact
#include <iostream>
using namespace std;
char spellings[][10]={"zero","one","two","three","four","five","six","seven","eight","nine"};
void print(int n){
if(n==0){
return;
}
print(n/10);
cout<< n << spellings[n%10]<<" ";
}
int main() {
print(234);
}

Explanation:

  • On line 4, we define an array spellings, which will store the string representation of each number. (
...