uksz
uksz

Reputation: 18699

Recursion in simple function

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?

Upvotes: 0

Views: 91

Answers (3)

Jay Kumar R
Jay Kumar R

Reputation: 537

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);

Upvotes: 0

Richard Chambers
Richard Chambers

Reputation: 17573

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);
    }
};

Upvotes: 1

anotherdev
anotherdev

Reputation: 2569

You call it in the wrong order. Revert that:

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

like this

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

Upvotes: 4

Related Questions