C PROGRAMMING PROGRAM • FUNCTIONS & RECURSION
Reverse a String Using Recursion
Learn how to reverse a string using recursion using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
recursion
Sample output
Reversed: noisrucer
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
#include <string.h>
void reverse(char text[], int left, int right)
{
if (left >= right) return;
char temporary = text[left]; text[left] = text[right]; text[right] = temporary;
reverse(text, left + 1, right - 1);
}
int main(void)
{
char text[200];
fgets(text, sizeof text, stdin);
text[strcspn(text, "\n")] = '\0';
reverse(text, 0, (int) strlen(text) - 1);
printf("Reversed: %s\n", text);
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Reversed: noisrucer
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Swap the outer characters and recursively process the smaller inner substring.
- Display the computed result.
Swap the outer characters and recursively process the smaller inner substring.
EFFICIENCY
Time and space complexity
Time complexity
O(n)
Auxiliary space
O(n)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
