AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Easyfor loopaccumulator

~90s

A product that keeps getting trimmed

What is printed?

Integer i, p
Set p = 1
For i = 1 to 5
    Set p = p * i
    If p > 20 Then
        Set p = p - 20
    End If
End For
Print p
Show the answer and the worked solution

Correct answer: B.

20

Worked solution

  1. i = 1: p = 1. i = 2: p = 2. i = 3: p = 6. None of these exceed 20.
  2. i = 4: p = 6 * 4 = 24, which is above 20, so p becomes 24 - 20 = 4.
  3. i = 5: p = 4 * 5 = 20, and 20 > 20 is false, so p stays 20 and 20 is printed.

Answer: 20.

The idea

A conditional adjustment inside the loop has to be applied on every pass. The strictness of the last comparison decides the answer, so read > and >= carefully.

Shortcut. Only the last two passes matter: 6 × 4 = 24 is trimmed to 4, then 4 × 5 = 20, which is not strictly above 20 and so stays.

Common trap. 120 is 5!, the product with the If ignored; the trim at i = 4 changes every later value.

A product that keeps getting trimmed — Aptitude Question

A product that keeps getting trimmed: What is printed? Answer and worked solution on CodeKairo.

Question

What is printed?

Integer i, p
Set p = 1
For i = 1 to 5
    Set p = p * i
    If p > 20 Then
        Set p = p - 20
    End If
End For
Print p

Options

  1. 4
  2. 20
  3. 100
  4. 120
Show the answer and the worked solution

Correct answer: B. 20

Worked solution

  1. i = 1: p = 1. i = 2: p = 2. i = 3: p = 6. None of these exceed 20.
  2. i = 4: p = 6 * 4 = 24, which is above 20, so p becomes 24 - 20 = 4.
  3. i = 5: p = 4 * 5 = 20, and 20 > 20 is false, so p stays 20 and 20 is printed.

Answer: 20.

The idea

A conditional adjustment inside the loop has to be applied on every pass. The strictness of the last comparison decides the answer, so read > and >= carefully.

Shortcut. Only the last two passes matter: 6 × 4 = 24 is trimmed to 4, then 4 × 5 = 20, which is not strictly above 20 and so stays.

Common trap. 120 is 5!, the product with the If ignored; the trim at i = 4 changes every later value.

All Pseudocode questions · placement mock tests