Problem Statement - Output Writing – For loop break
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);
Solution
TC++ #7226
Run Output
12
Loop initialization: a = 6, b = 4
First iteration:
Condition check: a <= 24 — 6 <= 24 —- true
Loop is executed for the first time
Loop execution: a % b which is 6 % 4 = 2 which is != 0 Hence, break is not executed
Loop increment operator: a = a+ 6 which is a = 6 + 6 which is 12
Second iteration:
Condition check: a <= 24 which is 12 <= 24 —- true
Loop is executed for the second time
Loop execution: a % b which is 12 % 4 which is 0 Hence, break is executed
Comes out of loop
System.out.println(a); 12
Output is 12 and loop is executed two times