Ejercicio
Reverso, recursivo
Objetivo
Cree un programa que use la recursividad para invertir una cadena de caracteres (por ejemplo, desde "Hello" devolvería "olleH").
Código de Ejemplo
// 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
}
}