Home > Mobile >  why this c program can't compile factorial
why this c program can't compile factorial

Time:11-29

#include <stdio.h>

int FAC(int a)
{
    if (a >= 1, a--)
    {
        return a   1 * a;
        FAC(a);
    }
}

int main() 
{
    int a = 0;
    int ret = 0;
    scanf("%d", &a);
    ret = FAC(a);
    printf("%d\n", ret);
}

if I input 5 the outcome is 8

But in the first function should't it be

5>=1 5-1 return 5*4 4>=1...

CodePudding user response:

First of all, you're returning a value before you're using recursion. The return keyword takes effect immediately, so all statements following this won't be executed.

Also, your factorial function does not actually calculate the factorial of a.

Examples for factorial functions:

Recursive

int factorial(int n) {
  if(n > 0) {
    return n * factorial(n - 1); // n! = n * (n-1) * (n-2) * ... * 1
  } else {
    return 1;
  }
}

Iterative

// Does exactly the same, just an iterative function
int factorial(int n) {
  int fac = 1;
  for(; n > 0; n--) {
    fac *= n;
  }
  return fac;
}

CodePudding user response:

Your factorial function (FAC) should ideally be something like:

unsigned int FAC(unsigned int a)
{
    // base condition - break out of recursion
    if (a <= 1)
        return 1;

    return a * FAC(a - 1);
}

unsigned int restricts range of argument to be in [0, UINT_MAX].

Do note that FAC returns a unsigned int, so you may be able to provide argument value up to 12, else there will be an overflow and you can see weird output.

BTW, UINT_MAX is defined in limits.h

CodePudding user response:

#include <stdio.h>  

int FAC(int a)
{
    if (a < 0) {
        return -1;
    } else {
        if (a == 0) {
            return 1;
        } else {
            return (a * FAC(a-1));
        }
    }
} 

int main()  
{  
  int a = 0;  
  int ret = 0;  
  scanf("%d", &a);   
  ret = FAC(a);
  if (ret == -1) {
    printf("%s\n", "Input was a negative integer.");
  } else {    
    printf("%d\n", ret); 
  }
}  
  •  Tags:  
  • c
  • Related