![]() |
|
[C] c++ recursive function - Printable Version +- Hack Forums (https://hackforums.net) +-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444) +--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151) +---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118) +---- Thread: [C] c++ recursive function (/showthread.php?tid=6049713) |
c++ recursive function - Norbi34 - Feb 15, 2020 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; } } RE: c++ recursive function - gurlhackerclub - Feb 15, 2020 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 RE: c++ recursive function - SIM-3991524 - Feb 23, 2020 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 RE: c++ recursive function - saltycracker - Feb 26, 2020 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. |