twitter
    Find out what I'm doing, Follow Me :)

Another Example Of Recursion

The program named backward.c is another example of recursion, so load it and display it on your screen.This program is similar to the last one except that it uses a character array.

main( )
{
char line_of_char[80];
int index = 0;
strcpy(line_of_char," this is a string.\n");
/* the leading space in this */
/* string is required so the */
/* the last character "t" in */
/* "this" is printed when */
/* the string is printed */
/* backwards due to the */
/* index being incremented */

/* to 1 before the the */
/* printf statement for */
/* printing the line back- */
/* wards */
forward_and_backwards(line_of_char,index);
}
forward_and_backwards(line_of_char,index)
char line_of_char[];
int index;
{
if (line_of_char[index]) {
printf("%c",line_of_char[index]);
index++;
forward_and_backwards(line_of_char,index);
}
printf("%c",line_of_char[index]);
}



Each successive call to the function named "forward_and_backward" causes one character of the message to be printed. Additionally, each time the function ends, one of the characters is printed again, this time backwards as the string of recursive function calls is retraced. Don’t worry about the character array defined in line 3 or the other new material presented here. After you complete chapter 7 of this tutorial, this program will make sense. It was felt that introducing a second example of recursion was important so this file is included here.

One additional feature is built into this program in the IBM PC version. If you observe the two calls to the function, and the function itself, you will see that the function name is spelled three different ways in the last few characters in the original IBM version. The IBM compiler doesn’t care how they are spelled because it only uses the first 8 characters of the function name so as far as it is concerned, the function is named "forward_". The remaining characters are simply ignored. If your compiler uses more than 8 characters as being significant, as does Hi-Tech, you will need to change two of the names so that all three names are identical, as we have done.

Compile and run this program and observe the results.