This is a C Program to reverse the string using recursion.
This C Program reverses the string using recursion.
This C Program uses recursive function & reverses the string entered by user in the same memory location. Eg: “program” will be reversed to “margorp”
Here is the source code of the C program to reverse a string. The C Program is successfully compiled and run on a Linux system. The program output is also shown below.
/* * C Program to Reverse the String using Recursion */ #include <stdio.h> #include <string.h> void reverse(char [], int, int); int main() { char str1[20]; int size; printf("Enter a string to reverse: "); scanf("%s", str1); size = strlen(str1); reverse(str1, 0, size - 1); printf("The string after reversing is: %s\n", str1); return 0; } void reverse(char str1[], int index, int size) { char temp; temp = str1[index]; str1[index] = str1[size - index]; str1[size - index] = temp; if (index == size / 2) { return; } reverse(str1, index + 1, size); }
In this C program we are reading a string using ‘str1[]’ array variable. Assign the value of the length of string using strlen() to size variable.
If condition statement is used to check that both the values of ‘index’ and ‘size’ variables are equal and divide the value by 2. If the condition is true then execute the statement and return the value.
Otherwise, if the condition is false then exit the statement. Again call the reverse() function by passing the value of ‘str1’ variable and the summation of the value of ‘index’ variable with 1 and the value of ‘size’ variable as argument. Print the reversed string from the given string.
$ cc pgm12.c $ a.out Enter a string to reverse: malayalam The string after reversing is: malayalam $ a.out Enter a string to reverse: cprogramming The string after reversing is: gnimmargorpc
Sanfoundry Global Education & Learning Series – 1000 C Programs.
Here’s the list of Best Books in C Programming, Data-Structures and Algorithms
- Apply for C Internship
- Practice BCA MCQs
- Check Computer Science Books
- Check C Books
- Apply for Computer Science Internship