Example:
Input: str = Algolesson Output: nosseloglA Input: str = GoodCode Output: edoCdooG
Reverse String Using Loop.
In this approach, we will reverse a string by using a loop that will iterate through the characters of the original string and build the reversed string character by character.
Below is the C implementation to reverse the string using for loop:
// C program to reverse the given string #include <stdio.h> #include <string.h> // function to reverse string void reverseString(char str[]) { 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; } } int main() { char str[100]; printf("Enter a string: "); scanf("%s", str); reverseString(str); printf("Reversed string: %s\n", str); return 0; }
Enter a string: Algolesson Reversed string: nosseloglA
Time Complexity: O(n)
Space Complexity: O(1)
Reverse String Using Recursion.
In this approach, we are going to use Recursion to reverse the given string.
Below C code implementation:
// C program to reverse the given string using recursion #include <stdio.h> void reverseString(char str[], int start, int end) { if (start >= end) { return; } char temp = str[start]; str[start] = str[end]; str[end] = temp; reverseString(str, start + 1, end - 1); } int main() { char str[100]; printf("Enter a string: "); scanf("%s", str); int length = strlen(str); reverseString(str, 0, length - 1); printf("Reversed string: %s\n", str); return 0; }
Enter a string: Welcome Reversed string: emocleW
In the recursive function, start and end represent the indices of the characters that need to be swapped. The function keeps swapping characters and recursively calling itself with the updated indices until the base case is reached.
Time Complexity: O(n)
Space Complexity: O(1)
No comments:
Post a Comment