C String Reversal Program
String reversal in C involves reversing the order of characters in a string. This can be achieved using different methods, including iterative and recursive approaches. Below, I will explain how to implement string reversal using both methods.
Method 1: Iterative String Reversal
In this approach, we swap characters from the beginning and end of the string, moving towards the center.
Implementation
Explanation of Iterative Method
Header Files:
#include <stdio.h>
: Includes standard input-output functions.#include <string.h>
: Includes string manipulation functions.
Function Definition:
void reverseStringIterative(char str[])
: This function takes a string as input and reverses it in place.
Variables:
left
: Pointer starting from the beginning of the string.right
: Pointer starting from the end of the string.
While Loop:
- The loop runs as long as
left
is less thanright
. - Characters at positions
left
andright
are swapped. - Both pointers move closer to the center.
- The loop runs as long as
Main Function:
- An array
str
is declared to hold the input string. - The user is prompted to enter a string using
fgets
to include spaces. - The
strcspn
function is used to remove any newline character from the string. - The reversal function is called, and the result is displayed.
- An array
Method 2: Recursive String Reversal
In this approach, we recursively reverse the string by swapping the first and last characters, then calling the function on the substring that excludes these two characters.
Implementation
Explanation of Recursive Method
Function Definition:
void reverseStringRecursive(char str[], int left, int right)
: This function takes a string and two indices (left
andright
) to reverse the string recursively.
Base Case:
- The recursion stops when the
left
index is greater than or equal to theright
index.
- The recursion stops when the
Swapping:
- Characters at positions
left
andright
are swapped.
- Characters at positions
Recursive Call:
- The function is called again with updated indices (
left + 1
andright - 1
).
- The function is called again with updated indices (
Main Function:
- The main function is similar to the iterative example, prompting for input and calling the recursive function to reverse the string.
How to Run the Program
Compile the Code: Use a C compiler like
gcc
to compile the code.Execute the Program:
Input Data: Enter a string when prompted.
Example Input/Output
Input:
Output:
Conclusion
String reversal is a common programming task that can be implemented using iterative or recursive methods in C. Both methods demonstrate the use of string manipulation, pointer arithmetic, and control flow in the C programming language.