C语言递归函数使用案例

递归函数

  • 函数自身调用自身,必须有结束条件退出循环

案例

  • 实现字符串逆序遍历
  • 实现斐波那契数列

代码示例:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
//递归函数     函数自身调用自身,     必须有结束条件  跳出循环
//1.实现字符串逆序遍历
void reversePrint(char*p)
{
        if (*p == '\0')
        {
               return; //退出条件
        }
        reversePrint(p + 1);
        printf("%c ",*p);
}
void test01()
{
        char*str = "abcdef";
        reversePrint(str);
}
//2.斐波那契数列 1 1 2 3 5 8 13
int fibonacci(int pos)
{
        if (pos == 1 || pos == 2)
        {
               return 1;
        }
        return fibonacci(pos - 1) + fibonacci(pos - 2);
}
void test02()
{
        int ret = fibonacci(7);
        printf("%d\n",ret);
}
int main()
{
        test01();
        //test02();
        return EXIT_SUCCESS;
}
posted @ 2022-02-13 12:51  黑马金牌编程  阅读(489)  评论(0)    收藏  举报