How the Code Works Function Logic:
The function print_backwards() reads a character from the user. If the character is not '.', the function calls itself recursively before printing the character. This means the function keeps calling itself until it reaches '.', without printing anything. How Recursion Works in This Case:
Each function call waits until the next character is processed. Once the recursion reaches '.', it stops calling itself and starts returning. As the function calls return in reverse order, characters are printed in reverse order. Step-by-Step Execution For example, if the user enters:
A B C D . The recursive calls and returns will happen as follows:
Step Input Character Action Stack (Call Stack)
1 'A' Calls print_backwards(), waits. A
2 'B' Calls print_backwards(), waits. A → B
3 'C' Calls print_backwards(), waits. A → B → C
4 'D' Calls print_backwards(), waits. A → B → C → D
5 '.' Stops recursion, prints "Output in reverse order:". A → B → C → D
6 - Prints 'D'. A → B → C
7 - Prints 'C'. A → B
8 - Prints 'B'. A
9 - Prints 'A'. (Empty)
Final Output:
Enter a character ('.' to end program): ABCD.
Output in reverse order: DCBA
Each function call reads a character but does not print it immediately. Recursive calls keep adding to the stack until '.' is reached. Once the base case ('.') is reached, function calls start returning. Characters are printed in reverse order as the stack unwinds. This is why the input is displayed in reverse when printed.