C# program to reverse String in C# using Iteration and Recursion
Here's a C# program that demonstrates how to reverse a string using iteration and recursion:
using System;
class Program
{
static void Main()
{
string inputString = "Hello, World!";
// Reverse using iteration
string reversedStringIteration = ReverseStringIteration(inputString);
Console.WriteLine("Reversed String (Iteration): " + reversedStringIteration);
// Reverse using recursion
string reversedStringRecursion = ReverseStringRecursion(inputString);
Console.WriteLine("Reversed String (Recursion): " + reversedStringRecursion);
}
static string ReverseStringIteration(string inputString)
{
char[] charArray = inputString.ToCharArray();
int start = 0;
int end = inputString.Length - 1;
while (start < end)
{
// Swap characters
char temp = charArray[start];
charArray[start] = charArray[end];
charArray[end] = temp;
start++;
end--;
}
return new string(charArray);
}
static string ReverseStringRecursion(string inputString)
{
if (inputString.Length <= 1)
{
return inputString;
}
return ReverseStringRecursion(inputString.Substring(1)) + inputString[0];
}
}
In this program, we have two methods: 'ReverseStringIteration' and 'ReverseStringRecursion'.
The 'ReverseStringIteration' method reverses the string using an iterative approach. It converts the input string to a character array and then uses two pointers, 'start' and 'end', starting from the beginning and end of the string, respectively. It swaps the characters at the 'start' and 'end' positions and continues moving towards the center until the pointers meet. Finally, it returns the reversed string.
The 'ReverseStringRecursion' method reverses the string using a recursive approach. It checks if the length of the input string is less than or equal to 1. If so, it returns the input string as is. Otherwise, it calls itself recursively with the substring starting from the second character, and then appends the first character at the end. This recursive process continues until the base case is reached, and then the reversed string is returned.
When you run the program, it will output:
Reversed String (Iteration): !dlroW ,olleH
Reversed String (Recursion): !dlroW ,olleH
Both the iterative and recursive methods correctly reverse the string "Hello, World!"