G
gdotone
From Dietel and Dietel
/* Fig. 8.13: fig08_13.c
Using gets and putchar */
#include <stdio.h>
void reverse( const char * const sPtr ); /* prototype */ 6
int main( void )
{
char sentence[ 80 ]; /* create char array */
printf( "Enter a line of text:\n" ); 12
fgets ( sentence, 80, stdin );
printf( "\nThe line printed backward is:\n" );
reverse( sentence );
return 0; /* indicates successful termination */
}/*endmain*/
/* recursively outputs characters in string in reverse order */
void reverse( const char * const sPtr )
{
/* if end of the string */
if ( sPtr[ 0 ] == '\0' ) { /* base case */
return;
} /* end if */
else { /* if not end of the string */
reverse( &sPtr[ 1 ] ); /* recursion step */
putchar( sPtr[ 0 ] ); /* use putchar to display character */
} /* end else */
} /* end function reverse */
I don't think I have a good grasp of when putchar( sPtr[ 0 ] ); get called.
recursively. the function reverse is called until the base case if found.
The pointer sPtr points to '\0'.
Let the sentence be Hello.
I get back olleH.
When is putchar called.
Thanks,
g.
/* Fig. 8.13: fig08_13.c
Using gets and putchar */
#include <stdio.h>
void reverse( const char * const sPtr ); /* prototype */ 6
int main( void )
{
char sentence[ 80 ]; /* create char array */
printf( "Enter a line of text:\n" ); 12
fgets ( sentence, 80, stdin );
printf( "\nThe line printed backward is:\n" );
reverse( sentence );
return 0; /* indicates successful termination */
}/*endmain*/
/* recursively outputs characters in string in reverse order */
void reverse( const char * const sPtr )
{
/* if end of the string */
if ( sPtr[ 0 ] == '\0' ) { /* base case */
return;
} /* end if */
else { /* if not end of the string */
reverse( &sPtr[ 1 ] ); /* recursion step */
putchar( sPtr[ 0 ] ); /* use putchar to display character */
} /* end else */
} /* end function reverse */
I don't think I have a good grasp of when putchar( sPtr[ 0 ] ); get called.
recursively. the function reverse is called until the base case if found.
The pointer sPtr points to '\0'.
Let the sentence be Hello.
I get back olleH.
When is putchar called.
Thanks,
g.