Computer Applications

Convert the following for loop segment to an exit-controlled loop.

for (int x = 1, y = 2; x < 11; x += 2, y += 2) {
    System.out.println(x + "\t" + y);
}

Java Iterative Stmts

2 Likes

Answer

int x = 1, y = 2;
do {
    System.out.println(x + "\t" + y);
    x += 2;
    y += 2;
} while (x < 11);

Reason — We need to convert the for loop given in question to a do-while loop as do-while is an exit-controlled loop whereas for and while are entry-controlled loop.

1. Initialization:

  • The variables x and y are initialized before the do-while loop: int x = 1, y = 2;.

2. Loop Body:

  • The statements inside the for loop are moved into the body of the do block:
    System.out.println(x + "\t" + y);
    x += 2;
    y += 2;
    

3. Condition Check:

  • The condition x < 11 is evaluated after executing the loop body, ensuring the loop is exit-controlled.

Answered By

1 Like


Related Questions