Java Program to check if entered number is palindrome or not
import java.util.Scanner;
public class PalindromCheck {
public static void main(String[] args) {
int reminder;
int n;
int d=0;
Scanner sc=new Scanner(System.in);
System.out.println("Enter number to check");
n=sc.nextInt();
int tempnum=n;
while(n>0)
{
reminder=n%10;
d=(d*10)+reminder;
n=n/10;
}
if(tempnum==d)
{
System.out.printf("Number %d is palindrome",d);
}
else
{
System.out.printf("Number %d is not palindrome",d);
}
}
}
Output
Enter number to check
121
Number 121 is palindrome
Enter number to check
233
Number 332 is not palindrome
public class PalindromCheck {
public static void main(String[] args) {
int reminder;
int n;
int d=0;
Scanner sc=new Scanner(System.in);
System.out.println("Enter number to check");
n=sc.nextInt();
int tempnum=n;
while(n>0)
{
reminder=n%10;
d=(d*10)+reminder;
n=n/10;
}
if(tempnum==d)
{
System.out.printf("Number %d is palindrome",d);
}
else
{
System.out.printf("Number %d is not palindrome",d);
}
}
}
Output
Enter number to check
121
Number 121 is palindrome
Enter number to check
233
Number 332 is not palindrome
- import java.util.Scanner-This statement tells the compiler to import Scanner class to program which is contained in utils package. The Scanner class has a methods defined to accept input entered by user.
- public class PalindromCheck - is the name of the class.
- public static void main(String[] args)- is the main() method which is the starting point of any Java Program.
- Next we declared the three integer variables reminder, n and d with d initialized to '0' . Next we created object of Scanner Class to accept value entered by user,and Prompted user to Enter the value.
- The value entered by user was stored in variable 'n' which is already declared. After that the value stored in 'n' is taken into another variable 'tempnum'.
- To check whether the number palindrome or not, We used WHILE loop and till the number is greater than ZERO , we take out the modules of the number , then we multiply variable 'd' with 10 and with adding reminder value which is stored in variable 'reminder'. And last we divide the number by 10 and store in same variable . This whole cycle is performed until the number entered is greater than ZERO.
- And finally we compare if the original number which was stored in variable 'tempnum' and the new number which is stored in 'd' matches or not. If they matches , then the number is palindrome. Other wise , the number is not palindrome.
Java Program to check if entered number is palindrome or not
Reviewed by LanguageExpert
on
August 21, 2017
Rating:
No comments