-5

I run this C++ code and it prints "ABACABA" on the screen.Can someone give me a detailed explanation of how recursive calls work in this example? I can`t understand why i get that output.

#include <iostream>
using namespace std;

void f( char c)
{
    if (c > 'A') f(c-1);

    cout << c;

    if (c > 'A') f(c-1);

}

int main()
{
    f('C');
}
Jarod42
  • 203,559
  • 14
  • 181
  • 302
user9163287
  • 1
  • 1
  • 1

1 Answers1

2
  • The ansi char "C" decremented is "B". C-- == B
  • The ansi char "B" decremented is "A". B-- == A

For the comparison:

  • B>A
  • C>A
  • C>B

I think you can follow the logic better, if you introduce a second std::cout as

#include <iostream>

void f(char c) {
    std::cout << " start " << c << "\n";
    if (c > 'A')
        f(c - 1);
    std::cout << c;
    if (c > 'A')
        f(c - 1);
}

int main() {
    f('C');
    return 0;
}

The output than reads as:

 start C
 start B
 start A
AB start A
AC start B
 start A
AB start A
A

I also suggest, that you use a debugger to do tasks like that.

schorsch312
  • 5,553
  • 5
  • 28
  • 57