C language learning: 14. Recursive functions

The so-called recursion means that the function calls itself

        Recursion is to break down big problems into small ones and divide and conquer;

        Recursive decomposition is a finite problem. Infinite problems cannot be recursed, which will cause the program to crash.

//数列求和
//Sn = a1 + a1 + ... + an
//Sn = Sn-1 + an, S1 = a1

Program example 1: Find cumulative sum

#include <stdio.h>

int sum(int n)
{
	int ret = 0;

	if (n == 1)
	{
		ret = 1;
	}
	else
		ret = sum(n - 1) + n;

	return ret;
}



int main()
{
	printf("sum = %d\n", sum(100));
	return 0;
}

Fibonacci sequence: 1, 1, 2, 3, 5, 8, 13, 21. . . . . .

当n>=3时,fac(n) = fac(n-1) + fac(n-2);
当n==2时,fac(n) = 1;
当n==1时,fac(n) = 1;

Program Example 2: Find the Fibonacci Sequence

#include <stdio.h>


int fac(int n)
{
	int ret = 0;
	if (n == 1)
	{
		ret = 1;
	}
	else if (n == 2)
	{
		ret = 1;
	}
	else if (n >= 3)
	{
		ret = fac(n - 1) + fac(n - 2);
	}
	else
		ret = -1;

	return ret;
}



int main()
{
	printf("fac(%d) = %d\n", 9,fac(9));
	return 0;
}

Guess you like

Origin blog.csdn.net/m0_49968063/article/details/133035239