Changing Iterative Code to Recursive
Learn how to change an iterative code to a recursive code.
We'll cover the following...
The key to transforming iterative code to recursive code is to find the specific lines of code that get transformed between the two implementations.
Count number of digits in a number
When given a number, the code must print how many digits are present in that number. The two implementations of the same code are shown below. First, look through the two codes and spot the differences. Then read the explanation to better understand this transformation process.
The illustration below explains this concept.
The code below shows the two types of code followed by an explanation.
The Code
class IterativeClass {public static int countDigits(int num) {int count = 1;while (num >= 10) {num = num / 10;count++;}return count;}public static void main( String args[] ) {int input = 1435043;int numDigits = countDigits(input);System.out.println("Number of digits in " + input + " = " + numDigits);}}
Transforming the Code
...