Home / Questions / Analyse the following program segment and determine how many times the loop will be executed and what will be the output of the program segment: int p = 200; while(true) { if(p < 100) break; p = p - 20; } System.out.println(p);
Explanatory Question

Analyse the following program segment and determine how many times the loop will be executed and what will be the output of the program segment:

int p = 200;

while(true)
{
    if(p < 100)
        break;
    p = p - 20;
}

System.out.println(p);

👁 127 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

Analysis of the loop:

Initial value of p = 200. The loop keeps subtracting 20 from p until p < 100. The loop executes as follows:

  • 1st iteration: p = 200 - 20 = 180
  • 2nd iteration: p = 180 - 20 = 160
  • 3rd iteration: p = 160 - 20 = 140
  • 4th iteration: p = 140 - 20 = 120
  • 5th iteration: p = 120 - 20 = 100
  • 6th iteration: p = 100 - 20 = 80

The loop stops when p becomes 80. The output will be:

Output:
80

The loop will be executed 6 times.