[Solved] why i can’t get factorial of a number? if i try it by taking else statement as return prod i get the correct answer


There are several problems with your code

  1. You have a return statement with no value within a function that is
    defined as returning type int
  2. Your function is a recursive one yet you are using a static variable
    that will live through invocations, making the output invalid with
    multiple function calls
  3. You are not handling the case where the input to your function is 0. This is the base case for what you are trying to achieve. You absolutely must consider the base case when writing a recursive function.

Code:

int recfac(int n)
{

    /* base case, ends recursive calls */
    if(!n) return 1;

    return n * recfac(n - 1);

}

Tested this code here for cases 1 – 9 and it gave the correct output.

EDIT: Also, main return type defaults to type int when no return type is specified and you have no return statement. You should include a return 0; statement to cease compiler warning.

0

solved why i can’t get factorial of a number? if i try it by taking else statement as return prod i get the correct answer