For the following function can one of you guys take a look and see if what I have at the bottom is correct..

void f(char ch)
{
     if (('A' <= ch) && (ch <= 'H'))
     {
           f(ch - 1);
           cout << ch;
     }
     else
          cout << endl;
}

Determine the output that will be produced by the following function calls
f('C')
I think it is B

f('G')
I think it is F

Recommended Answers

All 4 Replies

Hi jimJohnson :-)

Sorry to say, but you have got it wrong.

f is a recursive function, meaning that the function calls itself.

Let's have a look at what happens in this call:

f('B');

These are the steps in you algorithm.

f('B')
   if-statement evaluates to true.
      f('B' - 1)   //f('A')
         if-statement evaluates to true.
            f('A' - 1)   //f('@')
               if statement evaluates to false
                  cout << endl
            cout << 'A'
      cout << 'B'

Hope you can see what is going on. If not, I'll try to find more time later for a better explanation :-)

o ok I think I got it...So it takes C if it is true and since the if statement is less than or equal to A and we are subtracting one that means f(c = abc right and the other one is abcdefg?

if you want to simply stop at 1 less than the char you input then simply stop the recursive call and make it like this.

void f(char ch)

    {

     if (('A' <= ch) && (ch <= 'H'))

        {

              ch = ch -1;   // <-- see this?

              cout << ch;

        }

     else

     cout << endl;

     }
{

if (('A' <= ch) && (ch <= 'H'))

{

ch = ch -1; // <-- see this?

cout << ch;

}

else

cout << endl;

}

as posted by UberJoker

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.