Function to print string in reverse
Reversing a string
You can either print the string in reverse order - not modifying the original string, or you can reverse the string itself
Function to print the string in reverse order
If the string is hello, the function must print olleh.
This iterative function is quite straight forward. Find the length of the string, start from l-1 to 0. Print the characters.
void revprint(char *str)
{
int len = strlen(str);
len--;
do
putchar(str[len]);
while(len>=0);
}
We are using the condition len>=0 instead of >0, as we want to print 0th character too.
Now for the recursive function
void revprint(char *str)
{
char ch = *str;
if(ch)
revprint(str+1); //recursive call only if null char is not reached
putchar(ch);
}
Here the function is called recursively as long as we have not reached null character. Since we need reverse order, we first print next part of string and then print current character.
To modify and reverse the string instead, read Recursive and Iterative functions to reverse a String
Comments
Post a Comment