KnowledgeBoat Logo

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

3 Likes

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 to true 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;
}

Answered By

3 Likes


Related Questions