2(vi)
Give the output of the following program segment and mention how many times the loop is executed.
int K = 1;
do
{K += 2;
System.out.println(K);
} while (K <= 6);Show SolutionHide Solution↓
Number of times the loop is executed: 3 times
3
5
7
- The
do-whileloop executes the block first and then checks the condition. - Initial value:
K = 1- 1st iteration:
K = 1 + 2 = 3→ printed - Condition:
3 <= 6→ true
- 1st iteration:
- 2nd iteration:
K = 3 + 2 = 5→ printed- Condition:
5 <= 6→ true
- Condition:
- 3rd iteration:
K = 5 + 2 = 7→ printed- Condition:
7 <= 6→ false → loop stops
- Condition:
Hence, the loop executes 3 times.