Computer Applications
Consider the following program segment in which the statements are jumbled, choose the correct order of statements to check if a given word is Palindrome or not.
boolean palin(String w) {
boolean isPalin;
w = w.toUpperCase();
int l = w.length();
isPalin = false; // Stmt (1)
for (int i = 0; i < l / 2; i++) {
char c1 = w.charAt(i),
c2 = w.charAt(l - 1 - i); // Stmt (2)
if (c1 != c2) {
break; // Stmt (3)
isPalin = true; // Stmt (4)
}
}
return isPalin;
}
Java String Handling
1 Like
Answer
(4) (2) (1) (3)
Reason — To understand why the correct order is (4) (2) (1) (3), let’s analyze the program's purpose and the logic step by step. The goal of the program is to check if a given word is a Palindrome. A palindrome is a word that reads the same forward and backward, like "RADAR" or "LEVEL".
Steps in the Correct Order:
1. Statement (4): isPalin = true;
- We assume the word is a palindrome by setting
isPalintotrueat the start. This helps simplify our logic because we only need to find a mismatch to prove otherwise.
2. Statement (2): char c1 = w.charAt(i), c2 = w.charAt(l - 1 - i);
- In the loop, we pick one character from the start (
c1) and the corresponding character from the end (c2) of the word to compare them.
3. Statement (1): if (c1 != c2)
- If the characters do not match, the word is not a palindrome. To indicate this, we set
isPalin = false.
4. Statement (3): break;
- If we find even one mismatch, there’s no need to check further. We use
breakto exit the loop immediately.
Program segment with statements in correct order:
boolean palin(String w) {
boolean isPalin;
w = w.toUpperCase();
int l = w.length();
isPalin = true; // Stmt (4)
for (int i = 0; i < l / 2; i++) {
char c1 = w.charAt(i),
c2 = w.charAt(l - 1 - i); // Stmt (2)
if (c1 != c2) {
isPalin = false; // Stmt (1)
break; // Stmt (3)
}
}
return isPalin;
}
Answered By
1 Like
Related Questions
Write the output of the following String methods:
String x= "Galaxy", y= "Games";(a) System.out.println(x.charAt(0)==y.charAt(0));
(b) System.out.println(x.compareTo(y));
Which of the following returns a String?
- length()
- charAt(int)
- replace(char, char)
- indexOf(String)
Write a program in Java to enter any sentence. Also ask the user to enter a word. Print the number of times the word entered is present in the sentence. If the word is not present in the sentence, then print an appropriate message.