Changing Iterative Code to Recursive
This lesson will teach you how to convert iterative code to recursive.
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. The code below shows the two types of code followed by an explanation.
Print all Distinct Letters
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.
#include <iostream>#include <string>using namespace std;int main(){string name="Hello Worldd";//The first for loop which iterates over every characterfor(int i=0; i<name.length(); i++){int duplicate=0;char current = name[i];// The second for loop which removes all other duplicate occurencesfor(int j=i+1; j<name.length(); j++){if(current==name[j]){//Removing the duplicate occurenceduplicate = 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