Search⌘ K

Changing Iterative Code to Recursive

Explore how to convert iterative code into recursive functions by identifying loops, setting base cases, and passing parameters. This lesson helps you understand the step-by-step transformation process using practical C++ examples to improve your coding and interview skills.

The key to transforming iterative code to recursive code is to find the specific lines of code that get transformed between the two implementations. The code below shows the two types of code followed by an explanation.

Given a string, the code must print all the distinct letters, in the order that they appear. The two implementations of the same code are shown below. First, look through the two codes and spot the differences and then read the explanation to better understand the transformation process.

Iterative
Recursive
#include <iostream>
#include <string>
using namespace std;
int main(){
string name="Hello Worldd";
//The first for loop which iterates over every character
for(int i=0; i<name.length(); i++){
int duplicate=0;
char current = name[i];
// The second for loop which removes all other duplicate occurences
for(int j=i+1; j<name.length(); j++){
if(current==name[j]){
//Removing the duplicate occurence
duplicate = 1;
name= name.substr(0,j) + name.substr(j+1,name.length()-1);
}
}
if(duplicate==0){
cout<<current<<endl;
}
}
}

Transforming the Code

  • The first step is to identify the loop in the iterative code. This loop has two
...