C Program to Reverse a String with Example and Explanation
for (int i = 0; i < length / 2; i++) { char temp = str[i]; str[i] = str[length - i - 1]; str[length - i - 1] = temp; }.Examples
How to Think About It
Algorithm
Code
#include <stdio.h> #include <string.h> int main() { char str[100]; printf("Enter a string: "); fgets(str, sizeof(str), stdin); str[strcspn(str, "\n")] = '\0'; // Remove newline int length = strlen(str); for (int i = 0; i < length / 2; i++) { char temp = str[i]; str[i] = str[length - i - 1]; str[length - i - 1] = temp; } printf("Reversed string: %s\n", str); return 0; }
Dry Run
Let's trace reversing the string "hello" through the code.
Input string
str = "hello"
Calculate length
length = 5
First iteration (i=0)
Swap str[0] ('h') and str[4] ('o') -> str = "oellh"
Second iteration (i=1)
Swap str[1] ('e') and str[3] ('l') -> str = "olleh"
Loop ends
String reversed: "olleh"
| Iteration | i | str[i] | str[length - i - 1] | String after swap |
|---|---|---|---|---|
| 1 | 0 | h | o | oellh |
| 2 | 1 | e | l | olleh |
Why This Works
Step 1: Find string length
We use strlen to know how many characters the string has so we know where to stop swapping.
Step 2: Swap characters
Swapping characters from start and end moves the last character to the front and vice versa, reversing the string gradually.
Step 3: Loop only half the string
We only loop to the middle because swapping beyond that would undo the reversal.
Alternative Approaches
#include <stdio.h> #include <string.h> int main() { char str[100], rev[100]; printf("Enter a string: "); fgets(str, sizeof(str), stdin); str[strcspn(str, "\n")] = '\0'; int length = strlen(str); for (int i = 0; i < length; i++) { rev[i] = str[length - i - 1]; } rev[length] = '\0'; printf("Reversed string: %s\n", rev); return 0; }
#include <stdio.h> #include <string.h> void reverse(char *str, int start, int end) { if (start >= end) return; char temp = str[start]; str[start] = str[end]; str[end] = temp; reverse(str, start + 1, end - 1); } int main() { char str[100]; printf("Enter a string: "); fgets(str, sizeof(str), stdin); str[strcspn(str, "\n")] = '\0'; reverse(str, 0, strlen(str) - 1); printf("Reversed string: %s\n", str); return 0; }
Complexity: O(n) time, O(1) space
Time Complexity
The program loops through half the string length, so the time grows linearly with the string size, making it O(n).
Space Complexity
Swapping characters in place uses no extra memory besides a temporary variable, so space complexity is O(1).
Which Approach is Fastest?
In-place swapping is fastest and most memory efficient compared to using extra strings or recursion.
| Approach | Time | Space | Best For |
|---|---|---|---|
| In-place swapping | O(n) | O(1) | Memory efficient and fast |
| Using extra string | O(n) | O(n) | Keeping original string unchanged |
| Recursion | O(n) | O(n) | Elegant code but uses stack memory |