Home / Questions / (iv) Convert the given loop into exit controlled loop. int a, b; for ( a=10 , b=1; a>=1 ; a-=2) { b+=a; b++; } System.out.print(b);
Explanatory Question

(iv) Convert the given loop into exit controlled loop.

int a, b;

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

System.out.print(b);

👁 55 Views
📘 Detailed Answer
🕒 Easy to Read
Read the answer carefully and go through the related questions on the right side to improve your understanding of this topic.

Answer with Explanation

To convert the given for loop into an exit-controlled loop (i.e., a do-while loop), we need to ensure that the loop body executes at least once before checking the condition.

Converted Code Using do-while Loop:


int a = 10, b = 1;

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

System.out.print(b);

Explanation:

  1. Initialization: a = 10, b = 1

  2. Loop Execution: The loop executes at least once before checking a >= 1.

  3. Update: a is decremented by 2 in each iteration.

  4. Condition Check: The loop continues as long as a >= 1.

This ensures the loop behaves the same way as the original for loop but follows an exit-controlled structure.