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.
Write Your C# Exercise
C# Exercise Example
// 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)}");
}
}