Write a C program to find reverse of a string using recursion.
#include <stdio.h>
#include <string.h>
/* finds the reverse of the given input string using recursion */
void reverseString(char *string, char *res) {
if (*string) {
reverseString(string + 1, res - 1);
*res = *string;
}
return;
}
int main() {
char string[256], output[256];
/* get the input string from the user */
printf("Enter your input string:");
fgets(string, 256, stdin);
string[strlen(string) - 1] = '\0';
/* fill output with null */
memset(output, '\0', sizeof(output));
/* reverse the given input string and store the result in output */
reverseString(string, (output + strlen(string) - 1));
printf("Reverse of %s is %s\n", string, output);
return 0;
}
#include <string.h>
/* finds the reverse of the given input string using recursion */
void reverseString(char *string, char *res) {
if (*string) {
reverseString(string + 1, res - 1);
*res = *string;
}
return;
}
int main() {
char string[256], output[256];
/* get the input string from the user */
printf("Enter your input string:");
fgets(string, 256, stdin);
string[strlen(string) - 1] = '\0';
/* fill output with null */
memset(output, '\0', sizeof(output));
/* reverse the given input string and store the result in output */
reverseString(string, (output + strlen(string) - 1));
printf("Reverse of %s is %s\n", string, output);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter your input string:helloworld
Reverse of helloworld is dlrowolleh
Enter your input string:helloworld
Reverse of helloworld is dlrowolleh
No comments:
Post a Comment