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);
Views 16
Answer:
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.
Related Articles:
This section is dedicated exclusively to Questions & Answers. For an in-depth exploration of Java Programming Language, click the links and dive deeper into this subject.
Join Our telegram group to ask Questions
Click below button to join our groups.