Reputation: 19
#include <stdio.h>
void print_backwards();
int main()
{
printf("Enter a character ('.' to end program):");
print_backwards();
printf("\n");
return 0;
}
/***** Recursion function definition *****/
void print_backwards()
{
char character;
scanf("%c",&character);
if(character != '.')
{
print_backwards();
printf("%c",character);
}
else printf("\n\n Output in reverse order: ");
}
Output
Enter a character ('.' to end program):Hi.
Output in reverse order: iH
Please help me understand this recursive function usage in C program.
The main() function executes.
print_backwards() called 1st time.
It takes one character input, say 'H'
if() statement is true, hence
print_backwards() called 2nd time
It takes one character input, say 'i'
if() statement is true, hence
print_backwards() called 3rd time
It takes one character input, say '.'
if() statement is false, so it comes out of the braces under if() statement.In my understanding it skips printf("%c",character);
If so, how does it print the output in reverse?
EDIT1: This is after reading one of (Stackoverflow User) David C. Ranken's comments. Please correct me if I'm wrong.
The main() executes. print_backwards() called 1st time.
It takes one character input, say 'H'
if() statement is true, hence
print_backwards() called 2nd time
It takes one character input, say 'i'
if() statement is true, hence
print_backwards() called 3rd time
It takes one character input, say '.'
if() statement is false, so it comes out of the braces under if() statement and prints "Output in reverse order:" in a new line.
Now, the control of the execution comes back (not using return as it is confusing) to the place where print_backwards() was called lastly to continue its remaining lines of code, which at this point is before printf("%c",character);
This happens irrespective of return statement or return value available or not under print_baickwards()
Hope my statement is correct?
On continuing from printf("%c",character);
it prints 'i', the value of the variable character at that point in time.
The control of the execution goes back again to the place where it was called. Here again, it is printf("%c",character);
.However, now the value for the character variable is 'H'. It prints 'H'
and then the control of the execution goes back another time to printf("\n") under main()
Wherever I mention goes back, it is not because the respective function (print_backwards()) returns a value, but the control of the execution from the calling function has to execute the remaining lines of code under it.
Hope I've understood it correctly now?
Two more things,
i) Can main() be 'void' without 'return' statement?
Because, if it is so how will it inform the OS that it has done executing?
ii) When a user provides a string of input all at once in the beginning, the print_backwards() (function) is run so fast multiple number of times (according to the input given) such that a user fails to feel that it takes only one character from the input line each time the function is run.
Am I correct?
Upvotes: 0
Views: 65
Reputation: 59
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.
Upvotes: 0
Reputation: 16572
Each stack frame (if that's the right term) has its own instance of character
– it is not overwritten by recursive calls. So when an inner call returns to the outer function, it still remembers the character it had read before the recursive call. Since the returns are "inside out", i.e. they happen in reverse order of the calls, and since the printf() is called after each return from recursion, the timeline looks like this:
entry
│─ scanf(&char) <-- 'H'
│─ recurse
│ ├─ scanf(&char) <-- 'i'
│ ├─ recurse
│ │ ├─ scanf(&char) <-- '.'
│ │ └─ no recursion
│ │ ↙ return
│ └─ printf(char) --> 'i'
│ ↙ return
└─ printf(char) --> 'H'
Upvotes: 2