24 Feb 2024
Beginner
A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward. In other words, it remains unchanged when its characters are reversed. Palindromes can be found in various contexts, including words, sentences, numbers, and even entire verses or paragraphs.
Few examples of palindromes:
- Words: "radar", "level", "noon", "deified"
- Phrases: "A man, a plan, a canal, Panama", "Madam, in Eden, I'm Adam"
- Numbers: 121, 1331, 1221
- Sentences: "Able was I ere I saw Elba", "Was it a car or a cat I saw?"
In general, when determining if a sequence is a palindrome, spaces, punctuation, and character case are often ignored. The focus is on the sequence of characters themselves, ensuring that when read backward, they form the same sequence as when read forward.
using System;
class Program
{
// Entry point of the program
internal static void Main(string[] args)
{
// Test cases
string str1 = "radar";
string str2 = "hello";
// Check if the strings are palindromes
checkPalindrome(str1); // Output: Palindrome
checkPalindrome(str2); // Output: Not Palindrome
}
// Method to check if a string is a palindrome
static void checkPalindrome(string str)
{
bool flag = true; // Initialize flag as true initially
// Loop through the string from both ends towards the middle
for (int i = 0, j = str.Length - 1; i < str.Length / 2; i++, j--)
{
// Compare characters from both ends
if (str[i] != str[j])
{
flag = false; // Set flag to false if characters don't match
break; // Break the loop as we already found a mismatch
}
}
// Print the result based on the value of the flag
if (flag)
{
Console.WriteLine("Palindrome"); // If flag is true, it's a palindrome
}
else
{
Console.WriteLine("Not Palindrome"); // If flag is false, it's not a palindrome
}
}
}
Explanation:
- The
Mainmethod serves as the entry point of the program. - Two test cases (
str1andstr2) are created with strings "radar" and "hello" respectively. - The
checkPalindromemethod is called for each test case to determine if the strings are palindromes. - The
checkPalindromemethod checks whether a given string is a palindrome or not. - It iterates through the string from both ends towards the middle, comparing characters.
- If a pair of characters doesn't match, the method sets a boolean flag to
falseand breaks the loop. - After the loop, it prints "Palindrome" if the flag is
true, indicating the string is a palindrome; otherwise, it prints "Not Palindrome".
c-sharp
palindrome