walaa ahmed walaa ahmed -4 years ago 75
C Question

why in reverse function it work normal without using for loop for next character like ( sPtr[ count]( sPtr[ 2],if ( sPtr[ 3]...... and so on

#include <stdio.h>

void reverse( char sPtr[] ); /* prototype */

int main( void )
{
char sentence[ 80 ]; /* create char array */

printf( "Enter a line of text:\n" );

/* use fgets to read line of text */
fgets( sentence, 80, stdin );

printf( "\nThe line printed backward is:\n" );
reverse( sentence );
// system("pause");
return 0; /* indicates successful termination */
} /* end main */

/* recursively outputs characters in string in reverse order */
void reverse( char 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 */


this code to print string and its reverse like
james
semaj
but i cannot figure out why when passing ptr to array it could print whole string without for loop to make pointer indicate to next char to print it

Answer Source

The reverse function is what we call a "recursive" function. It calls itself as part of its operation.

The key pieces are:

  • sPtr[1] is the second character in the string, which means &sPtr[1] is a pointer to the string containing everything except the first character.
  • Calling reverse(&sPtr[1]) has the effect of doing whatever reverse does on a string containing everything except the first character.
  • calling reverse on an empty string prints nothing.

Recursive functions can be tricky to understand. I would consider this to be a bad example to learn from because the iterative approach (with a for loop) is so easy to understand and this version is so cryptic. There are other algorithms which are much more natural looking in recursive form.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download