For working professionals
For fresh graduates
More
5. Array in C
13. Boolean in C
18. Operators in C
33. Comments in C
38. Constants in C
41. Data Types in C
49. Double In C
58. For Loop in C
60. Functions in C
70. Identifiers in C
81. Linked list in C
83. Macros in C
86. Nested Loop in C
97. Pseudo-Code In C
100. Recursion in C
103. Square Root in C
104. Stack in C
106. Static function in C
107. Stdio.h in C
108. Storage Classes in C
109. strcat() in C
110. Strcmp in C
111. Strcpy in C
114. String Length in C
115. String Pointer in C
116. strlen() in C
117. Structures in C
119. Switch Case in C
120. C Ternary Operator
121. Tokens in C
125. Type Casting in C
126. Types of Error in C
127. Unary Operator in C
128. Use of C Language
Reversing a string in C is a fundamental problem every C programmer should be familiar with. While reversing a string is conceptually simple, it offers several opportunities to practice different programming concepts such as loops, recursion, memory manipulation, and pointer arithmetic.
By understanding this concept, you’ll not only get the string reversed but also gain insights into how strings are represented and manipulated in C, a powerful and low-level programming language.
Reversing a string essentially means swapping the characters at the beginning of the string with those at the end, moving towards the center. In C, strings are arrays of characters, so you can access and modify individual characters via their indices.
To reverse a string in C, we follow this general approach:
Let’s look at how we can do this using a loop.
#include <stdio.h>
#include <string.h>
void reverseString(char str[]) {
int start = 0;
int end = strlen(str) - 1;
char temp;
// Loop to swap characters
while (start < end) {
temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
int main() {
char str[] = "Hello, World!";
printf("Original String: %s\n", str);
reverseString(str);
printf("Reversed String: %s\n", str);
return 0;
}
Output:
Original String: Hello, World!
Reversed String: !dlroW ,olleH
Code Explanation:
This approach runs in O(n) time complexity, where n is the length of the string.
Enhance your C programming skills with our software development courses — take the next step in your learning journey!
There are several ways to reverse a string in C, and each method has its strengths. Let’s explore some of the most common and useful techniques.
The strrev() function is a library function that can be used to reverse a string in C. However, it is not part of the standard C library and is available only in some compilers, such as the Turbo C++ library.
Let’s look at how you would use this function if it's available:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
printf("Original String: %s\n", str);
// Using strrev() to reverse the string
strrev(str);
printf("Reversed String: %s\n", str);
return 0;
}
Original String: Hello, World!
Reversed String: !dlroW ,olleH
If you're working in an environment where strrev() isn’t available, you can write your own logic to reverse a string using loops or recursion.
Here’s how to do it manually using a for loop:
#include <stdio.h>
#include <string.h>
void reverseString(char str[]) {
int length = strlen(str);
for (int i = 0; i < length / 2; i++) {
// Swap characters
char temp = str[i];
str[i] = str[length - i - 1];
str[length - i - 1] = temp;
}
}
int main() {
char str[] = "Hello, World!";
printf("Original String: %s\n", str);
reverseString(str);
printf("Reversed String: %s\n", str);
return 0;
}
Original String: Hello, World!
Reversed String: !dlroW ,olleH
Original String: Hello, World!Reversed String: !dlroW ,olleH
Another method to reverse a string is by using recursion. This approach is elegant and reduces the need for explicit loops.
The base case would be when the string is empty or has only one character. The recursive case would be reversing the rest of the string and appending the first character at the end.
Code Implementation:
#include <stdio.h>
void reverseStringRecursively(char str[], int start, int end) {
if (start >= end) return; // Base case: If start meets or exceeds end, stop
// Swap characters
char temp = str[start];
str[start] = str[end];
str[end] = temp;
// Recursively call for the next characters
reverseStringRecursively(str, start + 1, end - 1);
}
int main() {
char str[] = "Hello, World!";
int length = strlen(str);
printf("Original String: %s\n", str);
reverseStringRecursively(str, 0, length - 1);
printf("Reversed String: %s\n", str);
return 0;
}
Original String: Hello, World!
Reversed String: !dlroW ,olleH
Using a for loop is another straightforward method to reverse a string. You can iterate through the string and swap characters, just like with the while loop.
Code Implementation:
#include <stdio.h>
#include <string.h>
void reverseStringForLoop(char* str) {
int i, length = strlen(str);
for (i = 0; i < length / 2; i++) {
char temp = str[i];
str[i] = str[length - i - 1];
str[length - i - 1] = temp;
}
}
int main() {
char str[] = "hello";
printf("Original String: %s\n", str);
reverseStringForLoop(str); // Reverse the string
printf("Reversed String: %s\n", str);
return 0;
}
Output:
Original String: hello
Reversed String: olleh
Explanation:
This method uses a for loop to iterate through the first half of the string, swapping each character with its counterpart from the second half.
A while loop can be used in much the same way as a for loop, with the added benefit of being more flexible in terms of controlling the loop conditions.
Code Implementation:
#include <stdio.h>
#include <string.h>
void reverseStringWhileLoop(char* str) {
int start = 0, end = strlen(str) - 1;
while (start < end) {
char temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
int main() {
char str[] = "hello";
printf("Original String: %s\n", str);
reverseStringWhileLoop(str); // Reverse the string
printf("Reversed String: %s\n", str);
return 0;
}
Output:
Original String: hello
Reversed String: olleh
Also Read: Top 9 Popular String Functions in C with Examples Every Programmer Should Know in 2025
Pointers in C provide a powerful way to manipulate strings. Using pointers to reverse a string can be more memory efficient as you directly operate on the string’s memory addresses.
Here’s how you implement pointers:
#include <stdio.h>
void reverseStringUsingPointers(char *str) {
char *start = str;
char *end = str;
// Move the 'end' pointer to the last character
while (*end != '\0') {
end++;
}
end--;
// Swap characters using pointers
while (start < end) {
char temp = *start;
*start = *end;
*end = temp;
start++;
end--;
}
}
Original String: Hello, World!
Reversed String: !dlroW ,olleH
Sometimes, you might want to reverse a string by copying its characters to another string in reverse order. If you want to keep the original string intact, you can reverse the string into another string.
Code Implementation:
#include <stdio.h>
#include <string.h>
void reverseStringUsingAnotherString(char *str) {
int length = strlen(str);
char reversed[length + 1]; // +1 for the null terminator
for (int i = 0; i < length; i++) {
reversed[i] = str[length - i - 1];
}
reversed[length] = '\0'; // Add null terminator
printf("Reversed String: %s\n", reversed);
}
int main() {
char str[] = "Hello, World!";
printf("Original String: %s\n", str);
reverseStringUsingAnotherString(str);
return 0;
}
Original String: Hello, World!
Reversed String: !dlroW ,olleH
This is the simplest way of reversing a string—without actually reversing it in memory. This method doesn’t modify the string itself, but it simply prints each character from the end of the string to the beginning, effectively displaying it in reverse order.
Here’s how you do it:
#include <stdio.h>
#include <string.h>
void printReverseOrder(char *str) {
int length = strlen(str);
for (int i = length - 1; i >= 0; i--) {
printf("%c", str[i]);
}
printf("\n");
}
int main() {
char str[] = "Hello, World!";
printf("Original String: %s\n", str);
printf("Reversed String: ");
printReverseOrder(str);
return 0;
}
Original String: Hello, World!
Reversed String: !dlroW ,olleH
There you go! Each method has its advantages and specific use cases depending on the environment. Mastering these will give you greater control over how you work with strings in C.
Also Read: Top 25+ C Programming Projects for Beginners and Professionals
Reversing a string in C is not without its challenges. While it seems like a straightforward task, there are several common mistakes and pitfalls that beginners may encounter.
Let’s explore some of them:
1. Forgetting to Null-Terminate the String
In C, strings are null-terminated, meaning they end with the \0 character. Suppose you forget to add the null terminator at the end of a string (especially when modifying or creating new strings). In that case, it can lead to undefined behavior and memory access errors.
Mistake Example:
pilers, is not part of the standard C library. Rel
Solution: Always ensure that strings are properly null-terminated after modification or creation.
2. Using Undefined Functions like strrev()
The strrev() function, which is commonly used in older compilers, is not part of the standard C library. Relying on this function can lead to portability issues, as not all compilers support it.
Mistake Example:
strrev(str); // Might not work on all compilers
Solution: Always use custom implementation methods or standard library functions like strlen() and strcpy() to ensure compatibility across different environments.
3. Overlooking Memory Allocation
When reversing a string into another string, ensuring enough memory is allocated for the new string, including the null terminator, is important. Failure to allocate sufficient memory can lead to buffer overflow and other issues.
Mistake Example:
char str[10];reverseString(str); // Not enough space for the reversed string
Solution: Always allocate enough space for the string, especially when manipulating or reversing it into another string.
4. Confusing Pointers with Array Indexing
In C, arrays and pointers are often interchangeable, but they aren't exactly the same. When using pointers to reverse a string, make sure to handle pointer arithmetic to avoid memory access errors correctly.
Mistake Example:
char *start = str;
char *end = str + strlen(str); // Incorrectly pointing to the null terminator
Solution: Always ensure that the end pointer points to the last valid character of the string, not the null terminator.
5. Incorrectly Handling Recursion Base Cases
When using recursion to reverse a string, it's critical to define a proper base case. Forgetting the base case can lead to infinite recursion and stack overflow.
Mistake Example:
void reverseStringRecursively(char str[], int start, int end) {
reverseStringRecursively(str, start + 1, end - 1); // No base case
}
Solution: Make sure that the base case checks when ‘start’ meets or exceeds ‘end’, terminating the recursion.
6. Using Inefficient Methods for Long Strings
For very large strings, some methods (like using additional strings or recursion) can be inefficient and lead to high memory usage or stack overflow errors. Avoid unnecessary copies and use in-place methods when dealing with long strings.
Mistake Example:
char reversed[strlen(str)]; // Creates an additional large array
reverseStringUsingAnotherString(str);
Solution: Use in-place reversal methods like the two-pointer approach or pointers to minimize memory overhead.
7. Not Handling Edge Cases (Empty Strings or Single Characters)
An empty string or a string of length one should be handled appropriately, but they are often overlooked. These edge cases may not cause errors, but they can affect program logic if not considered.
Mistake Example:
char str[] = ""; // Empty string
reverseString(str); // Function works, but it needs a check
Solution: Check for empty strings or strings with a single character early in the function and return immediately if no reversal is needed.
These common mistakes can lead to subtle bugs and unexpected behavior. By being aware of them and taking the necessary precautions, you can ensure that your string reversal logic is robust and error-free.
Test your understanding of the topic with the following multiple-choice questions. These questions focus on concepts related to reversing a string in C, including code output questions, string manipulation, and common pitfalls.
1. What is the output of the following code?
#include <stdio.h>
int main() {
char str[] = "Hello";
int length = strlen(str);
for (int i = length - 1; i >= 0; i--) {
printf("%c", str[i]);
}
return 0;
}
A) Hello
B) olleH
C) Error
D) Undefined behavior
2. Which of the following methods does not modify the original string during the reversal process?
A) Using recursion
B) Using an auxiliary string
C) Using two pointers
D) Using strrev()
3. What is the time complexity of reversing a string using the two-pointer approach (swapping characters from both ends)?
A) O(1)
B) O(n)
C) O(n^2)
D) O(log n)
4. What will happen if you try to reverse a string without checking its length first?
A) It will work for all cases.
B) It will work only for strings with even lengths.
C) It may lead to undefined behavior for empty or very short strings.
D) It will always cause a stack overflow.
5. What is the output of the following code?
#include <stdio.h>
int main() {
char str[] = "World";
strrev(str);
printf("%s", str);
return 0;
}
A) World
B) dlroW
C) Error
D) Undefined behavior
6. What is the purpose of the strlen() function in C when reversing a string?
A) To count the number of words in the string
B) To find the length of the string
C) To reverse the string
D) To append a null character at the end of the string
7. When using recursion to reverse a string, which of the following is necessary?
A) A loop that iterates over the string
B) A base case that stops the recursion
C) An auxiliary array to store the reversed string
D) A strrev() function
8. Which of the following methods uses extra memory to reverse a string?
A) Two-pointer approach
B) Using recursion
C) Using strrev()
D) Using an additional string
9. What would happen if you forget to terminate a string with a null character ('\0') after reversing it?
A) The program will still run fine.
B) It may lead to undefined behavior or incorrect string handling.
C) It will crash the program.
D) It will work only for strings of length 1.
10. Which of the following statements is true about reversing a string using pointers in C?
A) Pointers allow more efficient memory usage compared to arrays.
B) Pointers make it impossible to reverse strings.
C) Pointers require more code to implement string reversal.
D) Pointers cannot be used to swap characters in a string.
These MCQs will help you reinforce key concepts related to string reversal in C and test your understanding of different methods, their complexities, and common pitfalls.
Also Read: 25 Most Common C Interview Questions & Answers [For Freshers]
upGrad’s C programming courses offer comprehensive training, covering essential concepts such as loops, recursion, functions, and pointers. You’ll gain practical experience in writing efficient C programs, including tasks like factorial calculations, working with data structures, and optimizing algorithms.
Mastering C programming will provide you with a solid foundation for software development, competitive programming, and system-level programming.
Check out some of these upGrad courses to take your programming skills to the next level!
You can also get personalized career counseling with upGrad to guide your career path, or visit your nearest upGrad center and start hands-on training today!
Similar Reads:
Explore C Tutorials: From Beginner Concepts to Advanced Techniques
Addition of Two Numbers in C: A Comprehensive Guide to C Programming
String Anagram Program in C
C Program to check Armstrong Number
Array in C: Introduction, Declaration, Initialisation and More
Exploring Array of Pointers in C: A Beginner's Guide
What is C Function Call Stack: A Complete Tutorial
Discovering C Operators: An Overview with Types and Examples!
Binary Search in C
Conditional Operator in C
Constant Pointer in C: The Fundamentals and Best Practices
Constants in C Explained
Dangling Pointer in C: Causes, Risks, and Prevention Techniques
Find Out About Data Structures in C and How to Use Them?
C Program to Convert Decimal to Binary
The best method depends on the context. The two-pointer approach is efficient and operates in place, while recursion provides an elegant solution, and using strrev() is quick if available in your compiler.
No, strrev() is not part of the standard C library. It is available in some compilers like Turbo C, but for portability, it's better to implement your own reversal logic.
Yes, you can reverse a string using recursion. Instead of a loop, recursion repeatedly calls the function to swap characters from both ends of the string.
The time complexity for reversing a string is O(n), where n is the length of the string, as each character is visited and swapped only once.
For an empty string or a string with one character, the reversal logic should handle these cases by directly returning or doing nothing, as no reversal is needed.
The space complexity of the two-pointer method is O(1), as it works in-place and doesn’t require any additional space, aside from temporary variables for swapping.
Yes, pointers provide an efficient way to manipulate strings in C. You can reverse a string by using pointer arithmetic to access and swap characters at different positions in the string.
Common mistakes include forgetting to null-terminate the string, not properly handling negative indices in recursive functions, and failing to allocate enough memory when creating a new reversed string.
Recursion uses the system's stack to store intermediate function calls. For large strings, this can lead to a stack overflow if the recursion depth becomes too large.
Yes, you can use a for loop to reverse a string by iterating through the string and swapping characters from both ends, ensuring that the loop runs only until the middle of the string.
Yes, reversing a string is essentially the same as reversing an array since a string in C is an array of characters. Both require swapping elements (characters or array items) from opposite ends.
Take a Free C Programming Quiz
Answer quick questions and assess your C programming knowledge
Author
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.