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;
}
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
isPalin
totrue
at 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
break
to 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;
}
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));
Two strings,
city1
andcity2
, are compared usingcity1.compareTo(city2)
, and the result is less than zero. What does this indicate?Define a class to accept a string and convert the same to uppercase, create and display the new string by replacing each vowel by immediate next character and every consonant by the previous character. The other characters remain the same.
Example:
Input : #IMAGINATION@2024
Output : #JLBFJMBSJPM@2024Which of the following returns a value greater than or equal to 0?