What is the output of the following code? Please show each recursive step. #incl
ID: 3831433 • Letter: W
Question
What is the output of the following code? Please show each recursive step.
#include <iostream>
#include <string>
void function (string, int, int);
int main()
{
string mystr = “Hello”;
cout << mystr << endl;
function(mystr, 0, mystr.size());
return 0;
}
void function (string str, int pos, int size)
{
if (pos < size)
{
function(str, pos + 1, size)
cout << str[pos];
}
}
Explanation / Answer
The output is:
Hello
olleH
Recursion steps:
First pos is 0 and function is called.
function(str,0,5) -> function(str,1,5) -> function(str,2,5) -> function(str,3,5) -> function(str,4,5) -> function(str,5,5)
Now as pos<size is false, the call function(str,5,5) has nothing to do and returns
It goes back to function(str,4,5) and o is printed.
Then it goes back to function(str,3,5) and l is printed.
Then it goes back to function(str,2,5) and l is printed.
Then it goes back to function(str,1,5) and e is printed.
Then it goes back to function(str,0,5) and H is printed.
Now it returns to the main function.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.