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").
Example C# Exercise
Show C# Code
// 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
}
}
Output
Original: Hello
Reversed: olleH
More C# Programming Exercises of Functions
Explore our set of C# programming exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C#. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C#.
In this exercise of C#, you need to create two functions: one called WriteRectangle to display a filled rectangle on the screen using asterisks, and another ca...
In this exercise in C#, you need to create an iterative function that checks if a string is symmetric (a palindrome). A palindrome is a word, number, phrase, or other...
In this exercise in C#, you will need to create a recursive function to check if a string is symmetric (a palindrome). A palindrome is a word, number, phrase, ...
In this exercise in C#, you will need to write a function named "GetMinMax", which will ask the user to enter a minimum value (a number) and a maximum value (a...
In this exercise in C#, you will need to write two functions called "Multiply" and "MultiplyR" to calculate the product of two numbers using sums. The first ve...
In this C# exercise, you are asked to write a program where the main structure is the Main method. Inside this method, two functions should be called: SayHello...