Recursive in C

Recursion is the process of repeating an ingredient in the same way.

Recursion is the process of repeating an ingredient in the same way. Here is a general illustration:

 void tenhamdequi () { tenhamdequi (); /* goi chinh no */ } int main () { tenhamdequi (); } 

C programming language supports recursion, for example, a function can call itself. But when you use recursive functions, programmers need to carefully define conditions to exit a function, when an infinite loop is encountered.

Recursive iteration functions are useful for solving math problems such as calculating factorials, creating Fibonacci sequences, .

Calculate factorial in C

Here is an example, which can calculate the factorial of a given number using recursive function:

 #include int tinhgiaithua ( unsigned int i ) { if ( i <= 1 ) { return 1 ; } return i * tinhgiaithua ( i - 1 ); } int main () { int i = 10 ; printf ( "Gia tri giai thua cua %d la %dn" , i , tinhgiaithua ( i )); printf ( "n===========================n" ); printf ( "QTM chuc cac ban hoc tot! n" ); return 0 ; } 

Compile and execute the above C program to see the results:

Fibonacci sequence in C

Here's another example, creating the Fabonacci sequence for a given number using the recursive function:

 #include int day_fibonaci ( int i ) { if ( i == 0 ) { return 0 ; } if ( i == 1 ) { return 1 ; } return day_fibonaci ( i - 1 ) + day_fibonaci ( i - 2 ); } int main () { int i ; for ( i = 0 ; i < 10 ; i ++) { printf ( "%dt%n" , day_fibonaci ( i )); } printf ( "n===========================n" ); printf ( "QTM chuc cac ban hoc tot! n" ); return 0 ; } 

Compile and execute the above C program to see the results:

According to Tutorialspoint

Previous article: Handling errors in C

Next lesson: Variable parameter in C

Update 25 May 2019
Category

System

Mac OS X

Hardware

Game

Tech info

Technology

Science

Life

Application

Electric

Program

Mobile