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

Csc 115, Fall 2002 Final Exam 8. Coding Recursion and Iteration (12 marks) Write

ID: 3709688 • Letter: C

Question

Csc 115, Fall 2002 Final Exam 8. Coding Recursion and Iteration (12 marks) Write two Java methods (one recursive, the other iterative) as follows: ublic boolean isPalindrome (String msg) that, given a string msg, returns true, if and only if msg is the same string read backwards or forwards. All characters in the string are significant, but upper and lower case forms of the same letter are regarded as equal. For example, the call isPalindrome ("fred") returns false, the call isPalindrome ("anna") returns true, the call isPalindrome ( Anna") returns true, and the call isPalindrome ("Anna") (note the trailing space returns false. Hint To handle upper and lower case letters, see the API for the String class attached near the end of the exam. (d) Recursive solution: (6 marks) public boolean isPalindrome (String msg) t (e) Iterative solution: (6 marks) public boolean isPalindrome (String msg)

Explanation / Answer

Answer:

public boolean isPalindrome(String str){

// if length is 0 or 1 then String is palindrome

if(str.length() == 0 || str.length() == 1)

return true;

for(int i=0; i<str.length()/2; i++){

/*checking each character from front and back both are same or not. if not, strign is not palindrome*/

if(str.charAt(i) != str.charAt(str.length()-1-i))

{

return false;

}

}

/*if all characters from front anf nack then it is palindrome string.*/

return true;

}

public boolean isPalindrome(String str){

// if length is 0 or 1 then String is palindrome

if(str.length() == 0 || str.length() == 1)

return true;

if(str.charAt(0) == str.charAt(str.length()-1))

return isPalindrome(str.substring(1, str.length()-1));

return false;

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote