Home > Back-end >  C recursive function why this code return 6
C recursive function why this code return 6

Time:09-29

I am studying for an exam in C

I would like to know WHY THIS FUNCTION RETURN 6.

#include <iostream>
#include <string>

using namespace std;

int s(int n);

int main()
{
    int a;
    a = 3;

   cout << s(a);

    return 0;
}


int s(int n)
{
   if(n == 0) {
     return 1;
   }

   return s(n-1)*n;
}

The first passage n value is 3 and must be return 6. The second passage n value is 2 and must be return 4.

Why the final result is 6. Maybe cout print only the first value ?

Thank you for your help

CodePudding user response:

main() prints the return value of s(3).

s(3) returns s(2)*3

s(2) returns s(1)*2

s(1) returns s(0)*1

s(0) returns 1

Thus, the result of s(3) is (((1*1)*2)*3) = 6

CodePudding user response:

This is how recursion works.

I suggest you follow the code in your head, or on a piece of paper.

First, s() is called with 3. Since n is not 0, the function returns s(n-1)*n. n at this point is 3. To calculate s(n-1) that same function is called again (recursively), now with n-1, which is 2.

And so on...

  • Related