Home / Questions / Give the output of the following program segment and also mention the number of times the loop is executed: int a,b; for (a = 6, b = 4; a
Explanatory Question

Give the output of the following program segment and also mention the number of times the loop is executed:

int a,b;
for (a = 6, b = 4; a <= 24; a = a + 6)
{
    if (a%b == 0)
    break;
}
System.out.println(a);

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

Output of the above code is 12 and loop executes 2 times.

Explanation

This dry run explains the working of the loop.

a b Remarks
6 4 1st Iteration
12 4 2nd Iteration

In 2nd iteration, as a%b becomes 0 so break statement is executed and the loop exits. Program control comes to the println statement which prints the output as current value of a which is 12.

Loop Execution Analysis:

  1. Initialization:

    • a = 6

    • b = 4

  2. First Iteration:

    • Check condition a <= 24: 6 <= 24 is true.

    • Check a % b == 0: 6 % 4 == 0 is false.

    • Update a: a = a + 6 => a = 12.

  3. Second Iteration:

    • Check condition a <= 24: 12 <= 24 is true.

    • Check a % b == 0: 12 % 4 == 0 is true.

    • The loop breaks.