Problems understanding how recursion works in C

I learn functions in C from the book C Programming: A Modern Approach. It contains the following function:

int fact(int n)
{
  if (n <= 1)
    return 1;
  else
    return n * fact(n - 1);
}

with the following explanation:

To find out how recursions work, follow up on the execution of the statement i = fact(3);here's what happens: "

fact(3) finds that 3 is not equal or less than 1, so it calls
   fact(2)which finds that 2 is not equal or less than 1, so it calls
      fact(1) which finds that 1 is equal or less than 1, so it returns 1,causing
   fact(2) to return  2 x 1 = 2, causing
fact(3) to return 3 x 2 = 6

I'm really confused, why does he do all these actions if he is not inside the loop? why does he keep doing 3 less and less until he matches an argument in the if function?

Does the symbol * mean that n in fact (n) is now 3 - 1, and basically says that it all repeats itself again?

+1
source share
4 answers

- , . fact(n-1), , .

int fact(int n) //return value is an integer, name of function is "fact", input argument is an integer named n
{
  if (n <= 1) // if the input arg equals 1, return 1
    return 1;
  else 
    return n * fact(n - 1); //else, return n (input arg of this fact) times the return value of fact(n - 1)
}

, (3) 3 * 2 * 1 = 6. int a = fact(3):

fact(3) //dive into this function:
{
  if (n <= 1) //n is not 1
    return 1;
  else
    return n * fact(n - 1); //now we call fact(2)
}

(2):

{
  if (n <= 1) //n is not 1
    return 1;
  else
    return n * fact(n - 1); //now we call fact(1)
}

(1):

{
  if (n <= 1) //n equals 1
    return 1; //return 1
  else
    return n * fact(n - 1); 
}

fact(1) 1 , , fact(2). , return 2*fact(1);, return 3*fact(2);, , 'a' 6.

, , , .

+2

, 3

fact(3)

n = 3, else

3 * fact(2)

n = 2, else

2 * fact(1)

n = 1 , , 1

,

3 * fact(2)

3 * 2 * fact(1)

3 * 2 * 1 = 6

,

if(n = 1) /* 0! = 1 So you have reached the last iteration and you are good to return */
+1

, . , , , .. n <= 1, < 0! == 1.

3 n -

fact(n - 1) // n - 1 < n
0

, fact(n-1). , . , .

Btw, * .

0

Source: https://habr.com/ru/post/1651458/


All Articles