Home > database >  Why does my recursion code in c give an illogical answer
Why does my recursion code in c give an illogical answer

Time:03-17

when n= 5 it gives back 5 instead of 20, since 5>4 it should multiply 5*(5-1) and return it [Heres my code]

#include <stdio.h>

int factorial(int n) {

  if (n > 4)
    return (factorial(n - 1) * n);
  else
    return (1);
}

int main() {
  int n;
  printf("Please enter an integer: ");
  scanf("%d", & n);
  printf("Factorial(%d) = %d\n", n, factorial(n));
  return 0;
}

CodePudding user response:

That's not how a factorial works.

A Factorial Formula is: n! = n x (n - 1) x (n - 2) x ... x 1

  • 1! = 1
  • 2! = 2 x 1 = 2
  • 3! = 3 x 2 x 1 = 6
  • 4! = 4 x 3 x 2 x 1 = 24
  • 5! = 5 x 4 x 3 x 2 x 1 = 120
     if (n > 4)
          return (factorial(n-1)*n);
        else
          return(1);

When you input 5, in the next recursion, n becomes 4 it doesn't return factorial(n-1)*n) but returns a 1, hence the output will be 1 * 5 = 5.

CodePudding user response:

When you use recursive functions, you have to set you base conditions. Like in this example(factorial) that is just if (n == 0). So, you have to return 1 because you should not want continue to calculation. You return 1 if the number is lower than 4. This makes your output illogical. This is your modified code.

#include <stdio.h>
#include <stdlib.h>

int factorial(int n){
  
    if (n == 0)
        return 1;
    else {
        return(n * factorial(n - 1));
    }
}
    
int main(){
    
    int n;
    printf("Please enter an integer: ");
    scanf("%d", &n);
    printf("Factorial(%d) = %d\n", n, factorial(n));
    return 0;
}
  • Related