Here is the code with consistent indentation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
#include <stdio.h>
#define SIZE 80
void reverse(const char *const sPtr);
int
main(void)
{
char sentence[SIZE]; // create char array
puts("Enter a line of text:");
fgets(sentence, SIZE, stdin);
puts("\nThe line printed backward is:");
reverse(sentence);
}
// recursively outputs characters in string in reverse order
void
reverse(const char *const sPtr)
{
if ('\0' == sPtr[0]) { // base case
return;
} else {
reverse(&sPtr[1]); // recursion step
putchar(sPtr[0]); // use putchar to display character
}
}
|
Take the case where you pass "abc\n" into reverse.
- In the first call, sPtr is "abc\n".
- At line 21, reverse() calls itself recursively, passing "bc\n" as sPtr. Remember that arrays in C++ start at index 0, so the call reverse(& sPtr[1]) is passing the address of the second character in sPtr, not the first.
- The second call makes another recursive call, passing "c\n"
- The second makes a third, passing "\n" and the third makes a fourth, passing "".
Now keep in mind that each call
has its own copy of sPtr. The first call's sPtr pointer is a different variable from the second call's sPtr and the second call's sPtr is different from the third etc.
Okay, we were starting the fourth call, where sPtr == "". This triggers the base case, so the fourth call just returns to the third call.
- The third call continues at line 22 and prints sPtr[0]. The third call's sPtr points to "\n", so that's what it prints.
- The third call returns, causing the second call to continue at line 22. The second call's sPtr points to "c\n" so it prints 'c' and returns.
- That causes the second call to continue. It prints 'b' and returns
- That causes the first call to contine. It prints 'a' and returns.