Explain below program?
class PalindromeExample{
public static void main(String args[]){
int r,sum=0,temp;
int n=454;//It is the number variable to be checked for palindrome
temp=n;
while(n>0){
r=n%10; //getting remainder
sum=(sum*10)+r;
n=n/10;
}
if(temp==sum)
System.out.println("palindrome number ");
else
System.out.println("not palindrome");
}
}
Answers
Answer:
The class name is PalindromeExample. Public static void main(string args[]) is same as the main() function we use in c and cpp. It just means the syntax in java and nothing much. We need a number to check if it is palindrome or not. It is taken as n and the number is 454. A number is said to be palindrome if the number and its reverse is the same. That is, take another number 123. This number is not palindrome because 123 is not equal to 321. 454 is a palindrome number.
coming to the program logic:
We need to find the reverse of the number first. To get the last digit of 454, ie.4 , we use the statement n%10. The meaning of n%10 is that when the number n is divided by 10, we get the remainder and is saved in the variable r. This remainder is same as the last digit of the number.
To find the reverse of a number, we use the formula sum=(sum*10)+r. The meaning of the statement is we multiply each number with 10 inorder to make a shift in the position of the number. This is same as those we studied in lower classes. The ones place changes to tens place when multiplied by 10. So, sum=sum*10 is used to make a shift in the positions. Now, after making a shift in the position, we need to add the remainder(last digit of the number) into the place.
Divide the number by 10. After getting the last digit of that number, we need to get the previous digit. So, divide the number by 10.