-2

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;
}
VLAZ
  • 26,331
  • 9
  • 49
  • 67
Sa1and
  • 1
  • 1
  • Also useful: [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) and [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173) – VLAZ Mar 16 '22 at 18:09
  • Does it produce the corrct results for 1, 2, 3 and 4? – Paul Hankin Mar 16 '22 at 18:24
  • Change `if (n > 4)` to `if (n > 1)`. When passed `5` your function will only recurse once, the second call returns `1` to the first call, and that returns *1 x 5*, instead of *4! x 5*. – Weather Vane Mar 16 '22 at 18:26
  • 1
    "*it should multiply 5*(5-1)*" no, that's not what you've instructed it to do. Computers do what you tell them to, not what you want them to. You've instructed your program to do `5 * factorial(4)`. Now, what is `factorial(4)`? Hint, `4 > 4` is going to be false. – VLAZ Mar 16 '22 at 18:27

2 Answers2

1

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 > 1)
          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.

0

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;
}