Clever use of recursion to achieve reverse output of strings

There are many ways to make the input string output in reverse order. We can use string processing functions or exchange the elements in the character array. Here, we recursively encapsulate a string that can be output in reverse order. The function.

First of all, we know that the recursive program is recursively, and the program after the recursion must be executed at the end. Since we want to print the string in reverse order, the first character must be printed at the end. However, we are in reverse order. The address of the output function is also the address of the first character, so we can write it as

void reverse_string(char* string)
{
    
    
   reverse_string(string+1);	
   printf("%c",*string);
}

But recursion requires conditions. If there is no condition, it will recurse indefinitely. We have to find a condition to stop it.
We know that the last character of the string is ' \0 ' , then when we meet ' \0' , does it mean that there is no need to continue calling recursion?
Assuming it is possible, let's try the result

void reverse_string(char* string)
{
    
    
   if(*(string)!='\0')
   {
    
    
      reverse_string(string+1);
   }	
   printf("%c",*string);
}

If recursively to the last character, string + 1 is the address of '\0' . When the condition is not met, printing will start from '\0' , then all our efforts will be lost. So we have to make sure that the first character is not *'\0'* to determine whether the next character can be written as '\0'

void reverse_string(char* string)
{
    
    
   if(*(string+1)!='\0')
   {
    
    
      reverse_string(string+1);
   }	
   printf("%c",*string);
}

Can also be written as

void reverse_string(char* string)
{
    
    
	if (*(++string) != '\0')
	{
    
    
		reverse_string(string);
	}
	printf("%c",*(string-1));
}

Through such layers of recursion, we finally get the result we want.

Below is the schematic diagram of this recursive program and the code for reference:

void reverse_string(char* string)
{
    
    
	if (*(++string) != '\0')
	{
    
    
		reverse_string(string);
	}
	printf("%c",*(string-1));
}
int main()
{
    
    
	char arr[10] = "";
	scanf("%s",arr);
	reverse_string(arr);
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_52606524/article/details/113056750