✏️ Explanatory Question

Convert the following segment into an equivalent do- while loop.

int a, b;

for (a = 10, b = 20; b >= 10; b = b - 2) {
    a++;
}

👁 93 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation


int a = 10, b = 20;

do {
    a++;
    b = b - 2;
} while (b >= 10);

Explanation:

Initialization: The initialization part a = 10, b = 20 is executed before the do-while loop.

Loop body: The statement a++ is executed inside the loop body.

Update: The decrement of b (b = b - 2) is moved inside the loop body, after a++.

Condition: The while (b >= 10) condition is checked at the end, ensuring it’s executed at least once, like the for loop.

Convert the following segment into an equivalent do- while loop.

int a, b;

for (a = 10, b = 20; b >= 10; b = b - 2) {
    a++;
}
Visual aid for: Convert the following segment into an equivalent do- while loop. int a, b; for (a = 10, b = 20; b >= 10; b = b - 2) { a++; }