Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

FOR-LOOP: Using a for-loop, determine whether or not a word is a palindrome. A p

ID: 3545164 • Letter: F

Question

FOR-LOOP: Using a for-loop, determine whether or not a word is a palindrome. A palindrome is defined as a word that is spelled the same forwards and backwards, assuming the case DOES NOT matter. For example, racecar spelled backwards is racecar, and Hannah spelled backwards is hannaH, and both words are palindromes. Output whether or not a word input from a user is a palindrome (Hint: think of our for-loop example in class where we determined the backwards representation of an original word. If the original word equals the backwards word, the word is a palindrome).

Explanation / Answer

public static boolean palindromeFor(String s) {
int sLength = s.length();
int mid = sLength/2;
boolean isPalindrome = true;
// iterate until the mid point, position sLength-i+1 corresponds relatively to i
for(int i = 0; i < mid; i++) {
if(s.charAt(i) != s.charAt(sLength-i-1)) {
isPalindrome = false;
}
}
return isPalindrome;
}