Search⌘ K

Changing Iterative Code to Recursive

Explore how to transform iterative code into recursive methods by identifying loop logic and converting it into base cases and recursive calls. Understand this process through a Java example that counts the digits in a number, highlighting key differences and similarities between iteration and recursion.

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

Iterative
Recursive
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

...