Search code examples
c++recursionfactorial

I am trying to implement a program recursively. I just don't understand why my last line is being executed twice


Why is Hi being printed 4 times. It will just be executed once before the function finally returns the complete value.

#include <stdio.h>
int k = 0;
int factorial (unsigned int i) {
  if (i <= 1) {
    return 1;
  } else {
    k = i * factorial(i - 1);
  }
  printf("hi"); // Why is Hi being printed 4 times. 
  return k;
}

int main() {
  int i = 5;
  printf("Factorial of %d is %d\n", i, factorial(i));
  return 0;
}

Solution

  • Your printf's are probably getting queued as the function is trying to call itself.

    Let's examine it iteration by iteration -

    i = 5
    

    Iteration 1:

    k = 5 * factorial(4);
    

    Iteration 2:

    k = 4 * factorial(3);
    

    Iteration 3:

    k = 3 * factorial(2);
    

    Iteration 4:

    k = 2 * factorial(1);
    

    At this point, factorial(1) actually returns 1. Note that printf line is not reached in case.

    Now, this value is fed to k in iteration 4 and its returned back to its caller while doing a printf.

    The same happens in iteration 3, it receives a value in k and returns it to its caller i.e. iteration 2 while doing another printf

    Now, iteration 2 receives a value for k and returns it to its caller i.e. iteration 1 while doing yet another printf (3rd time!)

    Finally, iteration 1 receives a value for k and returns it, and along with that it does a final printf (Total 4)

    I hope that explains your issue! For ref: http://ideone.com/VgIwKX