0

I was wondering what a tail recursive factorial function would look like. In one of my lectures they said it should be pretty easy to implement, but I cant imagine how to implement it.

Thanks in advance!

zjweiss
  • 41
  • 3

1 Answers1

0

Just a basic C snippet:

unsigned int factorial(unsigned int n){
    if(n == 0){
        return 1;
    }
    else{
        return n * factorial(n - 1);
    }
}

Here, factorial() function is calling factorial() function again i.e. recursion.

  • I know GCC does tail recursion but the standard doesn't guarantee tail recursion, does it? – Jerry Jeremiah Dec 07 '20 at 04:50
  • 1
    This isn't a tail recursive factorial function, because it modifies the returned value from the recursive call. See [this answer](https://stackoverflow.com/a/2693719/5231607) to one of the marked duplicates for an example of a tail recursive factorial function. – 1201ProgramAlarm Dec 07 '20 at 05:54