Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

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.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote