Here's a step-by-step breakdown of how the function works:
The function
reversing_string()
takes a string as input.It checks if the input string is empty (
""
). If it is, an empty string is returned as the base case of the recursion.If the input string is not empty, the function makes a recursive call to
reversing_string()
with the argumentstring[1:]
. This slices the input string from the second character onward and passes it as an argument to the recursive call.The function continues to make recursive calls until it reaches the base case (an empty string).
Once the base case is reached, the function starts returning the reversed string by appending
string[0]
(the first character of the original string) to the reversed version of the remaining substring.The recursion unfolds, and each recursive call appends the characters from the original string in reverse order until the complete reversed string is built.
The final reversed string is assigned to the variable
str
.Finally, the reversed string is printed.
If you run this code, it will output:
dlroW olleH
How this line works: reversing_string(string[1:]) + string[0]
Hello World
ello World
llo World
lo World
o World
World
World
orld
rld
ld
d