Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Recursion

C Recursion

Recursion refers to the method of using the function itself within its own definition.

For example:


Once upon a time there was a mountain, and in the mountain there was a temple, and in the temple there was an old monk who was telling a story to a little monk! What was the story? "Once upon a time there was a mountain, and in the mountain there was a temple, and in the temple there was an old monk who was telling a story to a little monk! What was the story? 'Once upon a time there was a mountain, and in the mountain there was a temple, and in the temple there was an old monk who was telling a story to a little monk! What was the story? ...'"

The syntax format is as follows:

void

recursion

(

)

{

statements

; ... ... ...

recursion

(

)

;

/*

A function calls itself

*/

... ... ...

}

int

main

(

)

{

recursion

(

)

;

}

Flow diagram:

The C language supports recursion, meaning a function can call itself. However, when using recursion, the programmer needs to define a condition for exiting the function, otherwise it will enter an infinite loop.

Recursive functions play a crucial role in solving many mathematical problems, such as computing the factorial of a number, generating the Fibonacci sequence, and so on.

Factorial of a number

The following example uses a recursive function to compute the factorial of a given number:

Example

#include

<

stdio.h

double

factorial

(

unsigned

int

i

)

{

if

(

i

<=

1

)

{

return

1

;

}

return

i

factorial

(

i

1

)

;

}

int

main

(

)

{

int

i

=

15

;

printf

(

"

The factorial of %d is %f

\

n

"

,

i

,

factorial

(

i

)

)

;

return

0

;

}

When the code above is compiled and executed, it produces the following result:



15 的阶乘为 1307674368000.000000

Fibonacci Sequence

The following example uses a recursive function to generate the Fibonacci sequence for a given number:

Example

#include

<

stdio.h

int

fibonaci

(

int

i

)

{

if

(

i

==

0

)

{

return

0

;

}

if

(

i

==

1

)

{

return

1

;

}

return

fibonaci

(

i

1

)

fibonaci

(

i

2

)

;

}

int

main

(

)

{

int

i

;

for

(

i

=

0

;

i

<

10

;

i

++

)

{

printf

(

"

%d

\

t

\

n

"

,

fibonaci

(

i

)

)

;

}

return

0

;

}

When the code above is compiled and executed, it produces the following result:



0    

1    

1    

2    

3    

5    

8    

13    

21    

34