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.  

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.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button