0

Hello I'm a first year CS student attempting to understand why the return value is not '1' when using the Recursive function for example a simple Factorial function.

int factorial(int x) {
    if (x==1) {
    return 1;
    } else {
    return x * factorial(x - 1);
    }
}

I understand the factorial algorithm part but it eventually descends until it returns 1, so how does it return the answer instead of '1'???

  • Thank you to all who reply :)
  • Because it returns `x * factorial(x-1)` if `x > 1`. – user207421 May 29 '22 at 23:45
  • If you pass in `2`, then the `if` is false, so it goes to the recursive case. In that case, it calls the function with `1`, which indeed returns 1. However, that return value is then multiplied by 2, because the statement was `x * factorial(x - 1)` – ChrisMM May 29 '22 at 23:47
  • @ChrisMM ohhh okay, in lack of a better way to explain my understanding: it returns x * factorial(x - 1) which basically just stays there until it gathers all x values (recursively) and then in the end spits out the answer – Persianian2 May 29 '22 at 23:52
  • Correct. `factorial()` keeps being called until recursively `return 1` occurs, then the recursion unwinds. – user207421 May 30 '22 at 00:26
  • Short summary: recursive functions work exactly like non-recursive functions. – molbdnilo May 30 '22 at 07:24

0 Answers0