Mastering Recursion For Beginners [Part 4]
In this article, we will continue our series on recursion by looking at a problem that can be divided into two parts, I and II.
Part I is concerned with using recursion to find all numbers from 1 to n digits. For example, if n=2, then all numbers between 1 and 99 will be printed.
In Part II, we will deal with a variation of the problem where we want to print only a specific number, say n = 123 where we need to add some restrictions at digit position. To solve this problem, we will use a technique called digit dynamic programming.
Before we begin, let’s learn how to create an n+1 digit number from an n digit integer. Assume we have a number=2 and want to convert it to a two-digit number. To do this, we multiply the number by ten (2*(10)=20) and add all digits (0–9).
Print all numbers from 1 to ((10^N)-1) using GenerateNdigits(N,number=0).
Assume N=3. __a__|( b__ | c__ ).
Here, a, b, and c represent the hundredth, tenth, and unit’s position, respectively where a, b, and c can have values ranging from [0-9].
Assume I obtain all of the numbers from ( __b__ |__ c__.) (leap of faith). As a result, recursion will be used to complete this task.The only work which we need to do is to try all possible value of a from 0 to 9.
See the diagram below.
Essentially, we are starting with Leftmost Digit and instructing recursion to generate all number when we place starting digit say d(0–9) (leap of faith), as well as multiplying the number state in with 10 to produce the next (N-1) digits.
The code is as follows:-
Output(n==2):-