My C language learning diary 07 - function recursion

function recursion

make big things small 

 Two necessary conditions for recursion

  • There are restrictions, when the restrictions are met, the recursion will not continue
  • Getting closer and closer to this limit after each recursive call
    int main()
    {
    	printf("hehe\n");
    	main();
    	return 0;//循环一段时间后报错:stack overflow栈溢出
    }

 Practice accepting an integer value (unsigned) and printing each bit of it in order

void print(int n)//定义函数
{
	if (n > 9)//如果是两位数以上就调用函数,一位数就跳出打印
	{
		print(n / 10);//拆除n的末位数字在递归调用函数//定义函数到此处相当于循环体
	}
	printf("%d ", n % 10);//一位数打印本身,多位数打印末位数
}
int main()
{
	unsigned int num = 0;
	scanf("%d", &num);
	print(num);//调用函数
	return 0;
}

 

Writing a function does not allow the creation of temporary variables, find the length of the string 

int my_strlen(char* str)//循环计数
{
	int count = 0;//创建了临时变量,不符合要求
	while (*str != '\0')//遇到\0就停止计数
	{
		count++;//长度加一
		str++;//元素的地址后移一位
	}
	return count;
}
int main()
{
	char arr[] = "bit";//数组元素包括b i t \0
	int len = 0;
	len = my_strlen(arr);//数组只能传递首元素的地址
	printf("len=%d\n", len);
	return 0;
}

Improve with recursion

 //大事化小
 //my_strlen("bit");
 //1+my_strlen("it");
 //1+1+my_strlen("t");
 //1+1+1+my_strlen("");
 //1+1+1+0=3
int my_strlen(char* str)//               }
{                      //                |→相当于循环体
	if (*str != '\0')    //              |
		return 1 + my_strlen(str + 1);// }
	else
		return 0;
}
int main()
{
	char arr[] = "bit";
	int len = 0;
	len = my_strlen(arr);
	printf("len=%d\n", len);
	return 0;
}

 Recursion and iteration

Loop to find n factorial

int Fac(int n)
{
	int i = 0;
	int ret = 1;
	for (i = 1; i <= n; i++)
	{
		ret *= i;
	}
	return ret;
}
int main()
{
	int n = 0;
	int ret = 0;
	scanf("%d", &n);
	ret = Fac(n);
	printf("%d\n", ret);
	return 0;
}

Find the factorial of n recursively

int Fac(int n)
{
	if (n <= 1)
		return 1;
	else
		return n*Fac(n - 1);
}
int main()
{
	int n = 0;
	int ret = 0;
	scanf("%d", &n);
	ret = Fac(n);
	printf("%d\n", ret);
	return 0;
}

Find the nth Fibonacci sequence recursively

int Fib(int n)
{
	if (n <= 2)
		return 1;
	else
		return Fib(n - 1) + Fib(n - 2);
}
int main()//斐波那契数列是前两个数字的和等于第三个数字
{          //前两个数都是1
	int n = 0;
	int ret = 0;
	scanf("%d", &n);
	ret = Fib(n);
	printf("%d\n", ret);
	return 0;//效率太低
}

Implemented with a loop

int Fib(int n)
{
	int a = 1;
	int b = 1;
	int c = 1;
	while (n > 2)//必须知道前两个数才能算斐波那契数列,都为1
	{
		c = a + b;
		a = b;
		b = c;
		n--;//例n=4则需要循环求2两次,当n=4一次,当n=3一次
	}
	return c;
}
int main()
{          
	int n = 0;
	int ret = 0;
	scanf("%d", &n);
	ret = Fib(n);
	printf("%d\n", ret);
	return 0;//效率很高
}

Recursion and loop are selected according to the situation

Guess you like

Origin blog.csdn.net/qq_44928278/article/details/119647611