-5

Can someone explain to me why the output is 6? And what does the line return refun(a-1,b-1)*a; mean?

The code is below:

#include <iostream>
using namespace std;

long refun(int a, int b) {
    if (a >= 0 && b == 0)
        return 1;
    else if (a == 0 && b>0)
        return 0;
    else
        return refun(a - 1, b - 1)*a;
}

int main()
{
    int x = 3, y = 2;
    long z = refun(x, y);
    cout << z;
    return 0;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
zain3_5
  • 11
  • 2
  • 2
    What do you know about recursion? As for the result, try to step through the code, statement by statement and stepping into the recursive calls, to see what happens. To help I also suggest that instead of `return refun(a - 1, b - 1)*a;` you do something like `{ long result = refun(a - 1, b - 1); return result * a; }`, this way it's easier to see the result of the recursive call. – Some programmer dude Sep 26 '19 at 17:12
  • 1
    Beware that you have infinite recursion if you pass a negative value to `a` or `b`. – François Andrieux Sep 26 '19 at 17:14
  • The line `return refun(a-1,b-1)*a` means exactly what it says – "return the value of `refun(a-1,b-1)` multiplied by `a`". There is nothing special about recursion, it works exactly like if you called a different function. – molbdnilo Sep 26 '19 at 17:16
  • Any [decent C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) should cover the topic of recursion. – Remy Lebeau Sep 26 '19 at 20:55

2 Answers2

3

what does mean by this line return refun(a-1,b-1)*a;

A return statement return expr steps out of the function and returns the value the the expression to the caller.

refun is the name of a function, so refun(argument, list) calls the function and results of the expressions in the argument list are passed as parameters into the function. - is the subtraction operator and * is the multiplication operator that should be familiar to you from school.

Since refun calls itself, it is said to be recursive.

eerorika
  • 232,697
  • 12
  • 197
  • 326
1

return refun (a-1, b-1)*a;

There is a recursive call using refun () and the result returned is multiplied by the variable 'a'.

Recursive functions use something called “the call stack.” When a program calls a function, that function goes on top of the call stack.

Use this for your dry run and you would easily get 6.