Exercise
Function Reverse, Recursive
Objective
Write a C# program that uses recursion to reverse a string of characters (for example, from "Hello" it would return "olleH").
Write Your C# Exercise
C# Exercise Example
// Import the System namespace to use basic classes like Console
using System;
class Program
{
// Recursive function to reverse a string
public static string Reverse(string input)
{
// Base case: if the string is empty or has one character, return it as is
if (input.Length <= 1)
{
return input; // Return the string as is (base case)
}
// Recursive case: reverse the rest of the string and append the first character
return Reverse(input.Substring(1)) + input[0];
}
// Main method to test the Reverse function
public static void Main()
{
// Declare a string to be reversed
string original = "Hello";
// Call the Reverse function and store the reversed string
string reversed = Reverse(original);
// Print the reversed string to the console
Console.WriteLine($"Original: {original}"); // Expected: Hello
Console.WriteLine($"Reversed: {reversed}"); // Expected: olleH
}
}