In this article, we will write a C program to reverse a string using recursion. A function calling itself with smaller instances is called recursion. Recursion can be used for problems that can be broken down into smaller, similar problems.
C Program to reverse an input string using recursion
In this program, the recursive function, swaps first and last character of string, it then calls the function itself with smaller string (first and last character removed). The same process happens for the substring, it keeps happening until start >= end.
#include <stdio.h>
#include <string.h>
// Function to reverse a string using recursion
void reverseString(char* str, int start, int end) {
if (start >= end) {
return;
}
// Swap the characters at start and end
char temp = str[start];
str[start] = str[end];
str[end] = temp;
// Recursively calling the function with smaller instances
reverseString(str, start + 1, end - 1);
}
int main() {
////This array would hold the string upto 100 char
char str[100];
// Read the input string and store into str[]
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
// Remove newline from input string, if present
str[strcspn(str, "\n")] = '\0';
// Get the length of input string
int len = strlen(str);
// Calling the function to reverse string
reverseString(str, 0, len - 1);
// Print the reversed string
printf("Reversed string: %s\n", str);
return 0;
}
Output:
Enter a string: Chaitanya
Reversed string: aynatiahC
Explanation of the Program:
reverseString
() Function:- It takes three variables as parameters,
str
is for string,start
andend
represents the positions of characters in strings that needs to be swapped. - The base case for the recursion is when
start
is greater than or equal toend
, at this point, the recursion process ends. - In each recursive function call, the characters at positions
start
andend
are swapped, and then the function calls itself with the next set of indices (start + 1
andend - 1
). - The way the whole string gets reversed and when all the characters are swapped, the base case reaches and the recursion process stops.
- It takes three variables as parameters,
- Main Function:
- Read the user entered string using
fgets
. - Remove newline, if present using
strcspn
. - It determines the length of string using
strlen
. - The
reverseString
function is called with start index as0
and end index aslen - 1
. - Finally, the reversed string is printed.
- Read the user entered string using
Gabriel says
Hi I think it should be:
scanf (“%s”, string_array);
Because the string is already an address (&), right?