Hello,
I'm a beginner in C++ & I learn from the internet. I have come across this program which has recursive function to reverse a string.the program is short & intelligent.
I don't know how a recursive function actually works though I know it calls itself.the program is-
Iteration 1:
'h' goes to array index :0; Iteration 2:
't' goes to array index :1; Iteration 3:
'r' goes to array index :2....and so on...
And case 4 is:
Iteration 1:
'h' goes to array index :10; Iteration 2:
'h' goes to array index :9 & 't' goes to array index :10; Iteration 3:
'h' goes to array index :8 & 't' goes to array index :9; & 'r' goes to array index :10;....and so on...
Out of the 4 cases,which one is the correct way it works???
Please explain me as if I'm a five year old,it is tough to understand complex terms.
Any help would be appreciated.
Well, I suppose the answer is 3, but really, nothing goes to any array index as there is only one array present (which is the string). The function could be better called "print_in_reverse_order".
[edit]Oh wait, I'm a bit confused. You see, the output of iteration 2 happens before the output in iteration 1. Thus even though 'h' in 0 appears before 'S' in 9, the first iteration moves 'S'. That would make it Case 2.
Though if the output showed which char was added on that iteration, it would only show that char, and now it looks as if it shows the state of console.. (In that case none of the answers would be right, unless if you counted iterations in reverse order. Then it would be Case 3 )[/edit]
Anyway, to see what happens, you can substitute reverse with it's body:
Each time reverse is called, a call to cout << *s; is added to the stack. Then because of a stacks "First In Last Out" (FILO) order, you get the print statements executed in the reverse order they were added.
Think of it like a deck of cards. You start placing cards down, one on top of the other. Then as you pick them up, one at a time, you get them in the reverse order that you placed them. That's an example of a stack. And recursive function work in a very similar way.
I have one more doubt-
When I created a character pointer (*S) ,where did it point actually? to the starting alphabet "S" or the last alphabet "h"?
Because when I change my program to
1 2 3
if(*S!='/0')
reverse(S+2);
cout<<*(S);
OR
1 2 3
if(*S!='/0')
reverse(S+3);
cout<<*(S);
with different words,it gives confusing results.I am still a bit confused!
Let's look at your first code (one with +2)
For simplicity take a look at
1 2
cout<<*S;
if(*S!=0) reverse(S+2);
first.
If you call it with "abcd" If will print "ac". It clearly skips every other character.
Note that if you call it with "abcde" instead, you'll get "ace"+some garbage. This happens because '\0' then happens to be amongst the chars that are skipped.
And if you swap the lines back how they were, you'll get the same thing, just in reverse order.