[C Language] Function and Recursion Basic Topics

Calculate the factorial of n

image.png

recursion

//使用递归计算n的阶乘
#include<stdio.h>
int Jiecheng(int n)
{
    
    
	if (n<=1)
	{
    
    
		return 1;
	}
	else
	{
    
    
		return n * Jiecheng(n - 1);
	}
}
int main()
{
    
    
	int n = 0;
	scanf("%d", &n);
	int ret = Jiecheng(n);
	printf("%d", ret);
	return 0;
}

The red line is the call, the blue line is the return value.
image.png
The recursive execution process can be seen more clearly through the above picture.

cycle

int Jiecheng(int n)
{
    
    
	int count = 1;
	while (n>1)
	{
    
    
		count = count * n;
		n--;
	}
	return count;
}
int main()
{
    
    
	int n = 0;
	scanf("%d", &n);
	int ret = Jiecheng(n);
	printf("%d", ret);
	return 0;
}

Find the nth Fibonacci number. (overflow is not considered)

image.png

recursion

#include<stdio.h>
int Fib(int n)
{
    
    
	if (n>=3)
	{
    
    
		return Fib(n - 1) + Fib(n - 2);
	}
	else
	{
    
    
		return 1;
	}
}
int main()
{
    
    
	int n = 0;
	scanf("%d", &n);
	int ret = Fib(n);
	printf("%d", ret);
	return 0;
}

cycle

#include<stdio.h>
int Fib(int n)
{
    
    
	int a = 1;
	int b = 1;
	int c = 1;
	while (n>2)
	{
    
    
		c = a + b;
		a = b;
		b = c;
		n--;
	}
	return c;
}
int main()
{
    
    
	int n = 0;
	scanf("%d", &n);
	int ret = Fib(n);
	printf("%d", ret);
	return 0;
}

This blog mainly introduces how to use recursion and loops to solve problems, hoping to help you understand recursion and loops better.

Guess you like

Origin blog.csdn.net/weixin_63284756/article/details/130422635