Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

C 

c++ recursive function

Can someone explain me how this function returns 164618 for f(17).

void f(int x)
{
   if(x>3)
   {
       cout<<x-1;
       f(x/3);
       cout<<x+1;
   }
}
interesting, I do notice there is no new line character or space separator.

So the function outputs, x -1, which is 17 -1
16

Then the function calls itself with 17 divided by 3. This will be 5.
So you get 5 - 1 = 4 and 5+1 = 6

Then the function adds 1 to x and outputs
18

The output would be much easier to read if you added a new line or space.
example
cout<<x-1<< " ";
16 4 6 18
Its just the way you were using cout in f() that made it confusing

Try this example, should make a little more sense
Spoiler (Click to View)

Example output
Spoiler (Click to View)

All f() does is divide a number by 3 until it is less than 3
To understand recursion, you have to understand a function call. If you understand the basic mechanics of a function call then recursion is simply a function which calls itself.

Note: The topic of recursion(function recursion and recursive data structures) can get involved and very complicated but at its simplest, its really just a function call.
May you be given directions by software engineer document writers.


Possibly Related Threads...
Thread / Author Replies Views Last Post
[C] by FhackMar 2, 2022 03:52 AM 4 307 Mar 2, 2022 03:52 AM
Last Post: Fhack
[C] by SIM-3437924Aug 15, 2020 09:57 AM 1 184 Aug 15, 2020 09:57 AM
Last Post: SIM-3437924
[Python] by TerribleTy27Dec 7, 2018 07:56 AM 1 126 Dec 7, 2018 07:56 AM
Last Post: vorticalbox