palindrome in c#

In this program, You will learn how to check whether number is palindrome or not in C#, using a while loop, or for loop.

A number is a palindrome if the reversed number is equal to the original number. For example 121, 101, 12321 are palindrome numbers.

palindrome program in c# using for loop

using System;
class Palindrome {
  public static void Main() {
      int r,n,rev=0,copy;
      Console.Write("Enter the number:");
      n=int.Parse(Console.ReadLine());
      copy=n;
      for(;n>0;n=n/10)
      { 
        // It will find the reverse of the input entered by the user.
        rev=rev*10+n%10;
      }
      // Compare the reverse of input with the temporary variable
      if(copy==rev)
        Console.Write(copy+" is a palindrome number");
      else
        Console.Write(copy+" is a not palindrome number");
    }
}

palindrome program in c# using while loop

using System;
class Palindrome {
  public static void Main() {
      int r,n,rev=0,copy;
      Console.Write("Enter the number:");
      n=int.Parse(Console.ReadLine());
      copy=n;
      while(n>0)
      { 
        // It will find the reverse of the input entered by the user.
        rev=rev*10+n%10;
        n=n/10;
      }
      // Compare the reverse of input with the temporary variable
      if(copy==rev)
        Console.Write(copy+" is a palindrome number");
      else
        Console.Write(copy+" is a not palindrome number");
    }
}

output

Enter the number:121
121 is a palindrome number
Enter the number:123
123 is a not palindrome number

working of palindrome number in C#

  • In the above program, asked the user to enter a positive number which is store in the variable n
  • The number is saved into another variable copy to check it when we need to compare our original number with reverse number
  • Inside the loop, one by one last digit number is separated using code n%10 and rev*10 will maintain their nth position
  • After reversing the digits, compare a reverse value with the original value which is store in the copy variable
  • If the numbers are equal, then the number is a palindrome, otherwise, it's not.