Click here to Skip to main content
15,881,938 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
C#
#include<iostream>
#include<conio.h>
using namespace std;

int fun(int,int);
void main()
{
int x=3,y=5;
cout<<"the result is"<<fun(x,y);

    getch();
}
int fun(int a,int b)
{
    int box;
    if(b==1)
        return a;
    else
    return a+fun(a,b-1);
}




what is mean and what do this sentents { a+fun(a,b-1) }??



[edit] brought readability to title [/edit]
Posted
Updated 23-Apr-12 11:54am
v2
Comments
Philippe Mori 23-Apr-12 18:23pm    
Run the program under a debugger (or run it and change numbers) and it should be pretty easy to figure out what does the program do.

Now as this looks like a homework assignment, I am not giving away the clue. I am sure you will find the answer just by yourself. Here a couple of hints on the way.

So, if b is equal to 1, fun returns a. So much you have certainly figured.

If b is equal to 2, fun calls itself (yes it is a recursive function) and calculates fun (a, 2-1) which is a, as we saw above. Then it adds a, and hence the outer call of fun returns 2 * a.

Now try to figure what's going on if you call fun with b == 3, 4 ... You certainly see, what this leads up to.

Cheers!
 
Share this answer
 
v2
Comments
Anderso0on 23-Apr-12 18:51pm    
but why the fun do (2*a) why it do Multiplication
and the (a) befor fun what do???
Chuck O'Toole 23-Apr-12 18:57pm    
a+a = 2*a

Get a piece of paper and a pencil and "play computer" as you step through these calls, writing down all the intermediate answers.

Hint: Each time you "recurse" into the 'fun' function, you will get a new "a" to use inside 'fun' as when you return, the caller will still have their original "a".
This is the sort of "who gives a sh*t??" lump of code that's often chucked at you during interviews. One of the best ways of working out what it's doing is to refactor it so it's more readable (even on a bit of paper). One pass through gave me this:
C++
#include<iostream>
 
int fun( int a, int b )
{
    return a + (b == 1 ) ? 0 : fun( a, b - 1 );
}

int main()
{
    std::cout << "the result is" << fun( 3, 5 );
    char wait_for; std::cin >> wait_for;
}

When you do that the recursive function looks a lot simpler. To analyse what it does (a) work out where the recursion terminates and (b) work back up the call stack accumulating what each call has done. If you do that you won't need to dry run the code in a lot of cases as it's fairly obvious what's happening as soon as you know how many calls it makes.

Incidentally the "refactor to understand" technique is great to work out what code you've never seen before does AND it improves the quality of it. What's not to like?

Cheers,

Ash
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900