c递归二分法_C递归

c递归二分法

In the last tutorial I told you about the function calls i.e. call by value and call by reference. Today I will tell about the last advance feature of function i.e. recursion in C. So lets straight away starts it with a simple example.

Recursion in C


This is the simplest example of a recursive function. A function is said to be recursive function when it calls itself. In the above you can see the function crashp() is calling itself again and again.

What will be the output of the above program?
As you can see crashp() function is calling itself again and again. So this program will create an infinite loop and it will never end. In this case press Ctrl+PauseBreak button to stop the execution.

Note: It is quite difficult to show the working of recursive function. Therefore, I recommend you to read the basic concepts of functions first before proceeding further. Working of recursive function totally depends on the basic concepts.

Lets take another example of a recursive function to calculate factorial of a number.

Program for factorial using recursion in C

#include<stdio.h>
 
int factorial(int x)
{
   if(x<=1)
   {
      return 1;
   }
   return (x * factorial(x-1));
}
 
int main()
{
    int x=5;
    printf("Factorial of %d is %dn",x,factorial(x));
    return 0;
}


Output

Explanation

1. Program execution starts from the main() function. I have already assigned integer variable x with value 5.

2. After that I have written the printf() function.

3. Inside printf() function I have called factorial() function to calculate the factorial value.

4. Now the function factorial() will call itself until value of x makes this condition true (x<=1)

5. Consider the return statement of factorial() function carefully i.e. return x * factorial(x-1);

It will solve the answer in this way 5*4*3*2*1=120

Recursion in C
Image Source

Its quite tricky to understand the execution of a recursive function. But go through the above tutorial at least 2-3 times for better understanding. So this brings us to the end of functions. Now in the next tutorial I will tell you about the extended data types.

翻译自: https://www.thecrazyprogrammer.com/2015/01/recursion-in-c.html

c递归二分法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值