Let us see the java program to check the number is palindrome or not. so first we should know about palindrome. and logic to write a program, get to know about them below.
What is palindrome the number?
Content.
- What is palindrome the number.
- Logic for program.
- Program.
- Explanation.
- Output.
Palindrome number means if we give a number like 858, when the number is reversed we should get same number, 858.
Example:
our Input: 2002
Output: 2002
Logic for the Program.
- We need to display the last number first so, we divide(%) the number by 10 and take the reminder as answer.
- So, when we use that in a loop we get the Reversed number.
- And check whether the reversed number is equal to the given number, if it is equal, then number is palindrome. If not, it is not a palindrome.
Program
import java.io.*;
class pal
{
public static void main(String agr[]) throws IOException
{
int m,n,r,s=0;
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
System.out.println("Enter the number");
n=Integer.parseInt(in.readLine());
m=n;
while(n!=0)
{
r=n%10;
s=s*10+r;
n=n/10;
}
if(s==m)
System.out.println("The given number is palindrome, "+s);
else
System.out.println("The given number is not palindrome," +s);
}
}
Explanation.
- We have given the class name has pal.
- public static void main(String arg[]) refers to add a method i.e array of strong method to the program.
- int n,m,r,s is declaring the variable, s is declared to store 0.
- InputStreamReader read = new InputStreamReader(System.in); we create this object because we need to give the value to variable at the time of execution, this is a one of the way to give value to a variable.
- BufferedReader in = new BufferedReader(read); we create this object because, we need a buffer to store the value of the variable.
- n=Integer.parseInt(in.readLine()) is used to convert array of numbers to primitive integer.
- To check whether the reversed number is equal to the given number we use m=n.
- Now, we have to give condition which satisfies all the above int the logic for the program. I choose, While loop with n!=0 (n not-equal to 0)condition.
- n is the number we give.
- inside the loop ,
- to get reverse number, r=n%10
- to end the loop after reverse the number, s=(10*s)+r;
- to keep continue the loop for next number, n=n/10;
- And we should also use if statement to display the result.
- System.out.println is used to display the given in output screen(make sure S in System is capital)
Know more about if statement.
Know more about while loop here.
Output:
Compile : javac pal.java
Run : java pal
Enter the number
2552
The given number is palindrome, 2552.
Compile : javac pal.java
Run : java pal
Enter the number
8552
The given number is not palindrome, 2558.
known how to execute java program here.
Comments
Post a Comment