C# Palindrome of a Number
I have given here C# code to find out whether a given number is a palindrome or not.
Source Code
using System;
using System.Collections.Generic;
using System.Text;
namespace NP
{
class NumberPalindrome
{
static void Main(string[] args)
{
System.Console.WriteLine("\nProgram to check whether given number is palindrome or not. Enter -1 to exit");
while(true)
{
System.Console.Write("Enter a Number (-1 to exit): ");
string input = System.Console.ReadLine();
int n = 0;
try
{
n = Convert.ToInt32(input);
}
catch (System.Exception ex)
{
System.Console.WriteLine("Error in the input format\n\n");
continue;
}
if(n < 0)
break;
long number = n;
long index = 0;
bool palindrome = true;
int [] digits = new int [10];
do
{
digits[index++] = n % 10;
n = n / 10;
} while(n > 0);
for(int i = 0; i < index / 2 + 1; i++)
{
if(digits[i] != digits[index - 1 - i])
{
palindrome = false;
break;
}
}
if (palindrome == true)
System.Console.WriteLine("The number {0} is a palindrome\n", number);
else
System.Console.WriteLine("The number {0} is NOT a palindrome\n", number);
}
}
}
}Output
|