Programming Example
Strings and recursion
Strings and recursion
#include<stdio.h>
#include<string.h>
void display(char *str);
void Rdisplay(char *str);
int length(char *str);
main( )
{
char str[100];
printf("Enter a string : ");
gets(str);
display( str );
printf("\n");
Rdisplay(str);
printf("\n");
printf("%d\n",length(str));
}/*End of main()*/
void display(char *str )
{
if(*str == '\0')
return;
putchar(*str );
display(str+1);
}/*End of display()*/
void Rdisplay(char *str )
{
if(*str == '\0')
return;
Rdisplay(str+1);
putchar(*str );
}/*End of Rdisplay()*/
int length(char *str )
{
if(*str == '\0')
return 0;
return (1 + length(str+1));
}/*End of length()*/
Enter a string : atnyla
atnyla
alynta
6
Press any key to continue . . .
First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.