C recursive function (two): base conversion, string inversion, Fibonacci

C recursive function:

After the previous introduction of recursive functions (1): Introduction , we have a preliminary understanding of recursive functions, and know the pre-order recursion and post-order recursion. Next we look at some common applications of recursive functions.

Decimal to binary

We take a decimal number 13 and its binary number is 1101.
Trial code :

#include <stdio.h>

void bin(int n)
{
    
    
	int i = n % 2;	//十进制转换二进制就是不断对2取余数
	printf("%d\n",i);
	if(n>0)	{
    
    	//递归函数必须有个条件,否则将会一直循环
		bin(n / 2);	//递归调用
		}
}

int main()
{
    
    
	int i=13;
	bin(i);
	return 0;
}

The results of the operation are as follows
Insert picture description here
:

  1. The binary number of 13 is 1101, the display is 10110, the order is opposite to the correct one
  2. There is an extra 0 in front

Modify the previous code

#include <stdio.h>

void bin(int n)
{
    
    
	int i = n % 2;	//十进制转换二进制就是不断对2取余数

	if(n>0)//递归函数必须有个条件,否则将会一直循环
	{
    
    
		bin(n / 2);	//递归调用
		printf("%d",i);//把printf放在if里面,并且换成后序递归,去掉\n
	} 
}

int main()
{
    
    
	int i=13;
	bin(i);
	return 0;
}

Operation result:
Insert picture description here
success!
We use the post-order recursive function to complete the decimal conversion to binary

Decimal to Hexadecimal

According to the decimal conversion to binary, we try the following:

#include <stdio.h>

void hex(int n)
{
    
    
	int i = n % 16;	//把对2取余换成对16取余

	if(n>0)//递归函数必须有个条件,否则将会一直循环
	{
    
    
		hex(n / 16);	//递归调用
		printf("%d",i);
	} 
}

int main()
{
    
    
	int i=15;
	hex(i);
	return 0;
}

Operation result:
Insert picture description here
15 is no problem, but the letter F in hexadecimal should be a
simple and brainless solution:

#include <stdio.h>

char hex1(int n)		//因为字母ABC等不是数字,所以返回字符串char
{
    
    
	switch(n)
	{
    
    
	case 0:
		return '0';
	case 1:
		return '1';
	case 2:
		return '2';
	case 3:
		return '3';
	case 4:
		return '4';
	case 5:
		return '5';
	case 6:
		return '6';
	case 7:
		return '7';
	case 8:
		return '8';
	case 9:
		return '9';
	case 10:
		return 'A';
	case 11:
		return 'B';
	case 12:
		return 'C';
	case 13:
		return 'D';
	case 14:
		return 'E';
	case 15:
		return 'F';
	default:
		return '0';
	}
}

void hex(int n)
{
    
    
	int i = n % 16;	

	if(n>0)
	{
    
    
		hex(n / 16);
		printf("%c",hex1(i));//返回值变为char,所以改为%c
	} 
}

int main()
{
    
    
	int i=2348;//值改大一点
	hex(i);
	return 0;
}

Operation result:
Insert picture description here
look at the calculator:
Insert picture description here
success~~

String reverse

Let's look at an example of string reversal: the string '123456789' becomes '987654321'

#include <stdio.h>
#include <string.h>

//反转字符串
char *reverse(char *str) {
    
    
    int len = strlen(str);	//先计算字符串长度 
    if (len > 1) {
    
    			//对递归设立条件 
        char ctemp = str[0];	//把第一个字符暂存到ctemp
        str[0] = str[len - 1];	//把第一个字符换成最后一个字符
        str[len - 1] = '\0';  //最后一个字符在下次递归时不再处理
        reverse(str + 1);  //递归调用
        str[len - 1] = ctemp;
    }

    return str;
}

int main() {
    
    
    char str[20] = "123456789";
    printf("%s\n", reverse(str));
    return 0;
}

Operation result:
Insert picture description here
Let's analyze this process carefully:
every time the function is called, the 0th character of the string will be saved to the ctemp variable, and the last character will be filled to the position of the 0th character, and'\0' 'To fill in the position of the last character.

Readers should note that the actual parameter of calling reverse() is str+1, which will cause the point of the formal parameter str to change, and str will move backward by one character each time it is called recursively.

A conclusion can be drawn from the above two points: each recursive call will process a new substring. This new substring is formed on the basis of the original string.

Fibonacci sequence

The Fibonacci sequence is like this:
0, 1, 1, 2, 3, 5, 8, 13... The 0th item of this sequence is 0, and the first item is 1.
Starting from the second item, each item is equal to the sum of the previous two items.
We try to use recursion to generate such a series. For example, what is the tenth number in this series?

#include <stdio.h>

int fib(int n) 
{
    
    
	if(n == 0){
    
    	//因为第0项前面没有两项
		return 0;
	}
	if(n == 1){
    
     //因为第1项前面只有0一项,不能组成两项和
		return 1;
	}
	else
	{
    
    
		return fib(n-1)+fib(n-2); //递归调用
	}
}

int main() {
    
    
    printf("%d\n",fib(6));
    
    return 0;
}

Operation result:
Insert picture description here
The sixth item is 8, which is completely correct!

Sum of natural numbers

This example is relatively simple:

#include <stdio.h>

int sum(int n) 
{
    
    
	if(n>0)
	{
    
    
		return sum(n-1)+n;//调用递归
	}

}

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

Operation result: 5+4+3+2+1=15
Insert picture description here

to sum up

  • Using recursive functions can solve many problems that have a clear relationship.
  • Use pre-order and post-order to change the output order
  • Executing a recursive function will call itself repeatedly, and will enter a new layer each time it is called. When the innermost function is executed, it will exit from inside to outside layer by layer.

Guess you like

Origin blog.csdn.net/burningCky/article/details/109592324