+ 5
Can anyone explain me how could c variable store more than one character here? If it's because of recursion how recursion made?
#include <stdio.h> void reverseSentence(); int main() { printf("Enter a sentence: "); reverseSentence(); return 0; } void reverseSentence() { char c; scanf("%c", &c); if (c != '\n') { reverseSentence(); printf("%c", c); } }
5 ответов
+ 3
When you call recursion then a new instance of same function is created now maybe you know that two different block of code can have a variable with same name and can work independently due to scope of variable so actually it is creating different function in recursion stack so that c is different from another c they are stored in separate memory addresses
+ 2
Great explanation!
Thank you !YUGRAJ
+ 1
Inside main you have written printf statement after that reverseSentence() this function Calling after that control will jump to reverse function here u decleared one variable which type is char in next line u have written scanf so it will take one character as a input after taking input it will check if condition in condition u written c!='\n' means it will take input untill u will press enter line break after next line again function calling again it will take input one char this will run until u press enter line break and it will return values . Values will return in reverse order like if u input
a b c d e so final output will be
e d c b a
+ 1
I understood untill returning values thx!
But why in reverse order?
Can you explain plz?A.S.
+ 1
Learner🎖 hahaha /* your question about whether the recursive function "pauses", or keeps going, the answer is that when it makes another recursive call, it stops in its tracks until that call returns. This is the reason why your current code is printing
a b c d e
This happens because each function call stops when making the recursive call, and only wakes up again after that call has completely finished. This means that the smallest base case value gets printed first, then larger subsequent values get printed in reverse order.
e d c b a.........*/