Pages

Friday, May 3, 2013

C#: Palindrome

// declare and intialise a variable for storing length
int strLength = 0;
//declare and intialise a variable for represnting the first indexes of array
int intLength = 0;

//method for checking Palindrome or not  
public void CheckPalindrome(string str)
{

//get the string length
strLength = str.Length;
//Convert the string to lower case
str = str.ToLower();

//loop through all characters in string
while (intLength < strLength)
{

//check each character from first index equal to last index and
//continue through all characters in string
if (str[intLength] != str[strLength - 1])
{
//any characters not equal
Console.WriteLine("Not a Palindrome");
//quit loop
break;
}

//if characters are equal              
else
{
//increment to next index
intLength++;
//decrement string length to get last previous index
strLength--;


//if iteration completes and all characters are equal
if (intLength > strLength - 1)
{
 Console.WriteLine("Palindrome");
}

}

}

//input string: Refer
Output: Palindrome

//input string: word
Output: Not a Palindrome

No comments:

Post a Comment