Reverse a String Using Recursion in C
In this tutorial, we will write a recursive C program to reverse a string using recursion.
Problem Statement
Write a C program that reverses a string using a recursive function.
Concept of Recursion
Recursion is a process in which a function calls itself until a base condition is met.
To reverse a string recursively:
- Print the last character first.
- Then recursively call the function for the remaining string.
- Stop when the null character (
'\0') is reached.
C Program
#include <stdio.h>
void reverseString(char str[], int index) {
// Base condition
if (str[index] == '\0')
return;
// Recursive call
reverseString(str, index + 1);
// Print character during backtracking
printf("%c", str[index]);
}
int main() {
char str[100];
printf("Enter a string: ");
scanf("%s", str);
printf("Reversed string: ");
reverseString(str, 0);
return 0;
}
Explanation
1. Function Definition
The function reverseString() takes:
- The string
- The current index position
2. Base Condition
if (str[index] == '\0')
return;
When the null character is reached, recursion stops.
3. Recursive Call
reverseString(str, index + 1);
The function keeps calling itself until it reaches the end of the string.
4. Backtracking Step
printf("%c", str[index]);
Characters are printed while returning from recursion, which reverses the string.
Sample Input
Enter a string: hello
Output
Reversed string: olleh
Time Complexity
Each character is processed once. Therefore, the time complexity is O(n).
কোন মন্তব্য নেই:
একটি মন্তব্য পোস্ট করুন