search

Palindrome in C#

Sep 03, 2024 pm 03:34 PM
c#c# tutorial

Every college or university tends to give some exercise to its students. To make fun, the programs like palindrome are given to the students. Every programming language has its own way to write a program for palindrome. Many people may or may not be familiar with this concept. Do not worry about it. In the coming palindrome in c# article, you will understand what exactly palindrome is and how we can implement it programmatically.

Let’s talk about what is exactly palindrome means. Any number which is the same even if we make it reverse.

Ex: 1234321 => This number, even if you try to write in reverse order, gives you the same no.
More examples are 565,757, 99899, 52125 etc.

Now, let’s look at the exact Method to calculate it.

Suppose we have a no 434.
Now, let’s reverse it, and we get 434 only.

The funniest thing about palindrome is that if we add them, we will get a new palindrome no.

Ex: 214 + 412 = 626 (626 is nothing but the palindrome no.)
That simply means, if we are traversing no forward and backward, then also we are getting the same no.
There are certain ways to check palindrome in different languages. Here we are going to check with C#.

The Logic Behind Palindrome In C#

Simple logic used here traverses the serried of input backward and forward, and the given number or a string is the same as the initial than that corresponding output called a palindrome.

Look at the below program carefully, which takes the input from the user and checks whether it is a palindrome or not. This is very simple to identify once you know the concept of a palindrome.

Code:

using System;
public class IsPalindrome
{
public static void Main(string[] args)
{
int no,total=0,t,rev;
Console.Write("Please provide the no: ");
no = int.Parse(Console.ReadLine());
t=no;
while(no>0)
{
rev=no%10;
total=(total*10)+rev;
no=no/10;
}
if(t==total)
Console.Write("The given number is Palindrome.");
else
Console.Write("The given number is not Palindrome");
}
}

Output:

The output which asks for the user to enter any no.

Now, after entering no, it shows the no is a palindrome or not.

Palindrome in C#

In the above program, we took input from the user. We converted that input into the integer by parse method. With the help of a while loop, we reversed the no and checked it with the original no.

If the no provided by the user and the no which we reverser are the same, then that no is a palindrome. Here in our case, we took 212. And the output we got as the given number is a palindrome.

How to Check Palindrome in C# Using Various Methods?

Till now, we have checked only numbers that are a palindrome. But let me tell you we can check this with string also. Because of some combination of strings also has nature like a palindrome.

Example #1 – Madam

Let’s take this string, madam and reverse it, and we will find the same string.
It will be good to see by programmatically.

Code:

using System;
public class Palindrome {
public static void Main(string[] args) {
string inputStr, r;
inputStr = "Madam";
char[] letter = inputStr.ToCharArray();
Array.Reverse(letter);
r = new string(letter);
bool bool1 = inputStr.Equals(r, StringComparison.OrdinalIgnoreCase);
if (bool1 == true) {
Console.WriteLine("This string " + inputStr + " is a Palindrome!");
} else {
Console.WriteLine("This string " + inputStr + " is not a Palindrome!");
}
Console.ReadLine();
}
}

Output:

Palindrome in C#

Now, Let’s talk about the above program. What we actually did here.

We took one string here, which is nothing but the “Madam”. Then we converted that string into a character array. We used the ToCharArray() method to make a character array. After creating a character array, we have used the reverse method on that array to make it reverse. Then we compared both the given string and reversed string with the help of Equals() methods. We stored in the output of this method in a variable called bool1, which is of type Boolean.

Now, at the last, with the help of the if-else condition, we checked for the variable bool1 is equal to true or false. In our program, the if condition gets executed. Hence the output is “The string Madam is a palindrome.”

There is no limitation on finding the words or numbers.

You can make puzzles out of it. There are many conditions, like if you have one whole paragraph and someone asks you to check if there is any string that is a palindrome or not.

Some examples are like they have a paragraph, but the whole sentence itself is a palindrome.

Example # 2 – Was it a car or a cat I saw?

If we reverse the above sentence, then we get the same sentence again.

Let’s take an example; Please check out the below code.

Code:

using System;
public class Palindrome
{
public static bool IsPalindrome(string value)
{
int x = 0;
int y = value.Length - 1;
while (true)
{
if (x > y)
{
return true;
}
char i = value[x];
char j = value[y];
// Scan forward for a while invalid.
while (!char.IsLetterOrDigit(i))
{
x++;
if (x > y)
{
return true;
}
i = value[x];
}
while (!char.IsLetterOrDigit(j))
{
y--;
if (x > y)
{
return true;
}
j = value[y];
}
if (char.ToLower(i) != char.ToLower(j))
{
return false;
}
x++;
y--;
}
}
public static void Main()
{
string[] ary =
{
"Was it a car or a cat I saw?"
};
foreach (string value in ary)
{
Console.WriteLine("{0} = {1}", value, IsPalindrome(value));
}
}
}

Output:

Palindrome in C#

Hence, as we talked about, the whole sentence itself is a palindrome. If you reverse it also, it will give you the same sentence.

In the above program, we traverse through the sentence till the last. Then we made it to lowercase and checked against the given sentence. Try this program by coding yourself; then only you can understand the actual flow of these programs.

Conclusion

There are many tricks like a palindrome. We have seen the sting and number, which are palindrome in nature. How easily, with some steps, we achieved it.

The above is the detailed content of Palindrome in C#. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Developing with C# .NET: A Practical Guide and ExamplesDeveloping with C# .NET: A Practical Guide and ExamplesMay 12, 2025 am 12:16 AM

C# and .NET provide powerful features and an efficient development environment. 1) C# is a modern, object-oriented programming language that combines the power of C and the simplicity of Java. 2) The .NET framework is a platform for building and running applications, supporting multiple programming languages. 3) Classes and objects in C# are the core of object-oriented programming. Classes define data and behaviors, and objects are instances of classes. 4) The garbage collection mechanism of .NET automatically manages memory to simplify the work of developers. 5) C# and .NET provide powerful file operation functions, supporting synchronous and asynchronous programming. 6) Common errors can be solved through debugger, logging and exception handling. 7) Performance optimization and best practices include using StringBuild

C# .NET: Understanding the Microsoft .NET FrameworkC# .NET: Understanding the Microsoft .NET FrameworkMay 11, 2025 am 12:17 AM

.NETFramework is a cross-language, cross-platform development platform that provides a consistent programming model and a powerful runtime environment. 1) It consists of CLR and FCL, which manages memory and threads, and FCL provides pre-built functions. 2) Examples of usage include reading files and LINQ queries. 3) Common errors involve unhandled exceptions and memory leaks, and need to be resolved using debugging tools. 4) Performance optimization can be achieved through asynchronous programming and caching, and maintaining code readability and maintainability is the key.

The Longevity of C# .NET: Reasons for its Enduring PopularityThe Longevity of C# .NET: Reasons for its Enduring PopularityMay 10, 2025 am 12:12 AM

Reasons for C#.NET to remain lasting attractive include its excellent performance, rich ecosystem, strong community support and cross-platform development capabilities. 1) Excellent performance and is suitable for enterprise-level application and game development; 2) The .NET framework provides a wide range of class libraries and tools to support a variety of development fields; 3) It has an active developer community and rich learning resources; 4) .NETCore realizes cross-platform development and expands application scenarios.

Mastering C# .NET Design Patterns: From Singleton to Dependency InjectionMastering C# .NET Design Patterns: From Singleton to Dependency InjectionMay 09, 2025 am 12:15 AM

Design patterns in C#.NET include Singleton patterns and dependency injection. 1.Singleton mode ensures that there is only one instance of the class, which is suitable for scenarios where global access points are required, but attention should be paid to thread safety and abuse issues. 2. Dependency injection improves code flexibility and testability by injecting dependencies. It is often used for constructor injection, but it is necessary to avoid excessive use to increase complexity.

C# .NET in the Modern World: Applications and IndustriesC# .NET in the Modern World: Applications and IndustriesMay 08, 2025 am 12:08 AM

C#.NET is widely used in the modern world in the fields of game development, financial services, the Internet of Things and cloud computing. 1) In game development, use C# to program through the Unity engine. 2) In the field of financial services, C#.NET is used to develop high-performance trading systems and data analysis tools. 3) In terms of IoT and cloud computing, C#.NET provides support through Azure services to develop device control logic and data processing.

C# .NET Framework vs. .NET Core/5/6: What's the Difference?C# .NET Framework vs. .NET Core/5/6: What's the Difference?May 07, 2025 am 12:06 AM

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The Community of C# .NET Developers: Resources and SupportThe Community of C# .NET Developers: Resources and SupportMay 06, 2025 am 12:11 AM

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The C# .NET Advantage: Features, Benefits, and Use CasesThe C# .NET Advantage: Features, Benefits, and Use CasesMay 05, 2025 am 12:01 AM

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!