Pages

Thursday, April 4, 2019

Java Program To Print All Palindromes In A Given Range

Program To Print All Palindromes In A Given Range:

In this post, We will learn how to find all palindromes in a given range in java programming language.

First, We will learn what is palindrome?

What is Palindrome?

If a number is same as original number when it is reversed then it is said to be Palindrome.

Dictionary definition: a word, phrase, or sequence that reads the same backwards as forwards.

Java Program to print all palindromes in a given range

Palindrome Examples:

1001, 10101, 111, 99099

Now, We will write a program on how to print all palindromes in a given range of integers.

Objective: Given a range of numbers, print all palindromes in the given range.

Examples: 


Input range 1: {10, 100}
Output 1: 11, 22, 33, 44, 55, 66, 77, 88, 99

Input range 2: {10, 100}
Output 2: 202 212 222 232 242 252 262 272 282 292 303 313 323 333 343 353 363 373 383 393 

Input range 3: {1000, 1500}
Output 3: 1001 1111 1221 1331 1441 

Program to find all palindromes in a given range:

We will run this program running a for loop from min to max. For each number check whether a number palindrome or not. If number is palindrome then print it.



package examples.java.w3schools.array.programs;

/**
 * Java program to find all palindromes in a given range (min, max)
 * 
 * @author java-w3schools
 *
 */
public class PalindromesEx {

 public static void main(String[] args) {
  int min = 100;
  int max = 1500;

  printPal(min, max);
 }

 /**
  * Returns true if the given num is palindrome
  * 
  * @param num
  * @return
  */
 private static boolean isPalindrome(int num) {
  // Reversing a number
  int reverse = 0;
  for (int i = num; i > 0; i /= 10)
   reverse = reverse * 10 + i % 10;

  // If num and reverse are same, then num is palindrome
  return num == reverse;
 }

 /**
  * Prints palindrome between min and max
  * 
  * @param min
  * @param max
  */
 static void printPal(int min, int max) {
  for (int i = min; i <= max; i++)
   if (isPalindrome(i))
    System.out.print(i + " ");
 }
}



Output:

The above program produces this output.



101 111 121 131 141 151 161 171 181 191 202 212 222 232 242 252 262 272 282 292 303 313 323 333 343 353 363 373 383 393 404 414 424 434 444 454 464 474 484 494 505 515 525 535 545 555 565 575 585 595 606 616 626 636 646 656 666 676 686 696 707 717 727 737 747 757 767 777 787 797 808 818 828 838 848 858 868 878 888 898 909 919 929 939 949 959 969 979 989 999 1001 1111 1221 1331 1441





No comments:

Post a Comment

Please do not add any spam links in the comments section.