Q2.Given an array String[] array ={"civic","level","check","oop","boss","madam","sir"}, write down the
program with method which will print only palindromes from the array. You can use
public static Boolean ifPalindrome()
public static void printPalindrome() as reference.
Your Output should look like:
civic
level
madam
(A palindrome is a word, a sequence of characters which reads the same backward as forward, such as
refer)
public class Main {
public static boolean ifPalindrome(String word) {
for (int i = 0, j = word.length() - 1; i < word.length() / 2; i++, j--) {
if (word.charAt(i) != word.charAt(j)) {
return false;
}
}
return true;
}
public static void printPalindrome(String[] array) {
for (int i = 0; i < array.length; i++) {
if (ifPalindrome(array[i])) {
System.out.println(array[i]);
}
}
}
public static void main(String[] args) {
String[] array = {"civic", "level", "check", "oop", "boss", "madam", "sir"};
printPalindrome(array);
}
}
Comments
Leave a comment