AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Mediumfor loopbreakcontinue

~105s

Continue and Break in one loop

What is printed?

Integer i, s
Set s = 0
For i = 1 to 10
    If i MOD 3 == 0 Then
        Continue
    End If
    If i > 8 Then
        Break
    End If
    Set s = s + i
End For
Print s
Show the answer and the worked solution

Correct answer: B.

27

Worked solution

  1. The values 3, 6 and 9 are skipped by Continue and never reach either the Break test or the sum.
  2. The values 1, 2, 4, 5, 7 and 8 all pass both tests and are added: 1 + 2 + 4 + 5 + 7 + 8 = 27.
  3. At i = 10 the first test fails, the second succeeds because 10 > 8, and Break ends the loop.
  4. The value printed is 27.

Answer: 27.

The idea

Two guards in sequence must be applied in order: Continue can prevent Break from ever being tested, which is why i = 9 does not end the loop. Forgetting the Break gives 37, the sum of everything not divisible by 3.

Shortcut. Only i = 1 to 8 are ever added, so take 1 + … + 8 = 36 and remove the multiples of 3 in that range, 3 + 6 = 9: 36 − 9 = 27.

Common trap. 37 adds 10 as well, missing that i = 10 passes the MOD test and then triggers Break because 10 > 8.

Continue and Break in one loop — Aptitude Question

Continue and Break in one loop: What is printed? Answer and worked solution on CodeKairo.

Question

What is printed?

Integer i, s
Set s = 0
For i = 1 to 10
    If i MOD 3 == 0 Then
        Continue
    End If
    If i > 8 Then
        Break
    End If
    Set s = s + i
End For
Print s

Options

  1. 22
  2. 27
  3. 30
  4. 37
Show the answer and the worked solution

Correct answer: B. 27

Worked solution

  1. The values 3, 6 and 9 are skipped by Continue and never reach either the Break test or the sum.
  2. The values 1, 2, 4, 5, 7 and 8 all pass both tests and are added: 1 + 2 + 4 + 5 + 7 + 8 = 27.
  3. At i = 10 the first test fails, the second succeeds because 10 > 8, and Break ends the loop.
  4. The value printed is 27.

Answer: 27.

The idea

Two guards in sequence must be applied in order: Continue can prevent Break from ever being tested, which is why i = 9 does not end the loop. Forgetting the Break gives 37, the sum of everything not divisible by 3.

Shortcut. Only i = 1 to 8 are ever added, so take 1 + … + 8 = 36 and remove the multiples of 3 in that range, 3 + 6 = 9: 36 − 9 = 27.

Common trap. 37 adds 10 as well, missing that i = 10 passes the MOD test and then triggers Break because 10 > 8.

All Pseudocode questions · placement mock tests