Print the given string in reverse order in C
Understanding String Reversal
Reversing a string means changing its character order from end to start.
We will explore three different methods to reverse a string in C.
Method 1: Using a Loop
This method iterates through the string from end to start and prints the characters.
#include <stdio.h> #include <string.h> void reverseString(char s[]) { int len = strlen(s); for (int i = len - 1; i >= 0; i--) { printf("%c", s[i]); } printf("\n"); } int main() { char str[] = "hello"; reverseString(str); return 0; }
Output: olleh
Method 2: Using Recursion
This method reverses the string using recursion.
#include <stdio.h> #include <string.h> void reverseRecursively(char s[], int index) { if (index < 0) { printf("\n"); return; } printf("%c", s[index]); reverseRecursively(s, index - 1); } int main() { char str[] = "world"; reverseRecursively(str, 4); return 0; }
Output: dlrow
Method 3: Using String Reverse Function
This method uses a built-in function to reverse the string.
#include <stdio.h> #include <string.h> int main() { char s[] = "example"; strrev(s); printf("%s\n", s); return 0; }
Output: elpmaxe