0

I am having the following function:

void test(const char *nap){
if (*nap != 'D'){
    test(nap+1);
    std::cout << *nap;
}};

When I call the function with:

"ABCD"

Output, that I thought I would get was: ABC, however, in reality, its CBA. Can anyone explain to me where do I make mistake?

6
  • 2
    The stack unwinds and you're calling the recursion before printing. So, the first to print would be C, the stack unwinds one and prints B and so on. Commented Feb 3, 2016 at 20:02
  • @ChiefTwoPencils, oh, okay. I am C++ beginner, and had no idea that it works that way. Commented Feb 3, 2016 at 20:03
  • It's helpful to draw out on paper what's happening with the recursion when facing problems with its behavior. Commented Feb 3, 2016 at 20:03
  • @ChiefTwoPencils, can you expand your comment into answer? Commented Feb 3, 2016 at 20:04
  • 1
    @uksz - This video explains how recursion works youtube.com/watch?v=ygK0YON10sQ Commented Feb 3, 2016 at 20:04

3 Answers 3

4

You call it in the wrong order. Revert that:

test(nap+1);
std::cout << *nap;

like this

std::cout << *nap;
test(nap+1);
Sign up to request clarification or add additional context in comments.

Comments

1

Your recursion is to go to the end of the text string and to then go backwards printing each character.

In other words your function keeps calling itself until it reaches end of string. At that point it returns to where it called itself and the next step is to print the current character.

Then you return to where it called itself again and the next step is to print the current character.

The result is that you traverse the string until the end of string by the recursive calls. Once you reach the end of string you start unwinding the series of recursive calls. At each return you print the current character.

Try the following which will print the current character and then call itself to print the next character instead. When it reaches the end of the string it will unwind the recursive calls.

void test(const char *nap) {
    if (*nap != 'D'){
        std::cout << *nap;
        test(nap+1);
    }
};

Comments

0

because the std::cout is after calling the recursion ( )..

test(nap+1);
std::cout << *nap;

That is parent feeds children before eating.

The below will get what you want:

 std::cout << *nap;
 test(nap+1);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.