Output Writing – For loop break – Computer Sir Ki Class

Login


Lost your password?

Don't have an account ?
Register (It's FREE) ×
  

Login
[lwa]



Exam Questions-ICSE2017-02D #JAVA#7226    siteicon   siteicon  

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


Share

CSKC| Created: 15-Apr-2019 | Updated: 26-Nov-2019|ICSE2017









Back