Exercise
Function Palindrome, Recursive
Objective
Write a C# recursive function to say whether a string is symmetric (a palindrome). For example, "RADAR" is a palindrome.
Example C# Exercise
Show C# Code
// Import the System namespace to use basic classes like Console
using System;
class Program
{
// Recursive function to check if a string is a palindrome (symmetric)
public static bool Palindrome(string str)
{
// Convert the string to uppercase to make the comparison case-insensitive
str = str.ToUpper();
// Base case: if the string has one or zero characters, it's a palindrome
if (str.Length <= 1)
{
return true;
}
// Compare the first and last characters
if (str[0] != str[str.Length - 1])
{
return false; // If they are not equal, it's not a palindrome
}
// Recur with the substring excluding the first and last characters
return Palindrome(str.Substring(1, str.Length - 2));
}
// Main function to test the Palindrome function
public static void Main()
{
// Test case 1: "RADAR"
string testString1 = "RADAR";
Console.WriteLine($"Is \"{testString1}\" a palindrome? {Palindrome(testString1)}");
// Test case 2: "HELLO"
string testString2 = "HELLO";
Console.WriteLine($"Is \"{testString2}\" a palindrome? {Palindrome(testString2)}");
// Test case 3: "madam"
string testString3 = "madam";
Console.WriteLine($"Is \"{testString3}\" a palindrome? {Palindrome(testString3)}");
}
}
Output
Is "RADAR" a palindrome? True
Is "HELLO" a palindrome? False
Is "madam" a palindrome? True
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 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...
In this C# exercise, you are asked to write a program where the Main method must be like this:public static void Main(){ SayHello("John"...
In this C# exercise, you are asked to write a program where the Main method must be like this:public static void Main(){ int x = 3;
In this C# exercise, you are asked to write a program where the Main method must be like this:public static void Main(){ Console.WriteLi...