for loop
Check for Palindrome Number with for loop
In this example we shall show you how to check if a palindrome number exists in an array, using a for loop. A palindrome number is a number that is equal to its reverse number. To check if a palindrome number exists in an array, using a for loop one should perform the following steps:
- Create an array of the numbers to be checked. The numbers of the example are int numbers.
- Loop through the array of the numbers to check if a palindrome number exists.
- For every number in the array, reverse it and check if it is equal to its reverse number,
as described in the code snippet below.
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | package com.javacodegeeks.snippets.basics; public class CheckForPalindromeNumberWithForLoop { public static void main(String[] args) { // numbers to check int numbers[] = new int []{ 252 , 54 , 99 , 1233 , 66 , 9876 }; // loop through the given numbers for ( int i = 0 ; i < numbers.length; i++) { int numberToCheck = numbers[i]; int numberInReverse = 0 ; int temp = 0 ; // a number is a palindrome if the number is equal to it's reversed number // reverse the number while (numberToCheck > 0 ) { temp = numberToCheck % 10 ; numberToCheck = numberToCheck / 10 ; numberInReverse = numberInReverse * 10 + temp; } if (numbers[i] == numberInReverse) { System.out.println(numbers[i] + " is a palindrome" ); } else { System.out.println(numbers[i] + " is NOT a palindrome" ); } } } } |
Output:
252 is a palindrome
54 is NOT a palindrome
99 is a palindrome
1233 is NOT a palindrome
66 is a palindrome
9876 is NOT a palindrome
This was an example of how to check if a palindrome number exists in an array, using a for loop in Java.