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

~60s

A loop that steps by seven

How many times does the body of the loop execute?

Integer i, c
Set c = 0
For i = 5 to 50 step 7
    Set c = c + 1
End For
Print c
Show the answer and the worked solution

Correct answer: B.

7

Worked solution

  1. i takes the values 5, 12, 19, 26, 33, 40 and 47.
  2. The next value would be 54, which is above 50, so the loop stops.
  3. That is 7 executions of the body, so 7 is printed.

Answer: 7.

The idea

For a loop from a to b with step s the count is floor((b − a) / s) + 1. Listing the values is quicker under exam pressure and immune to the off-by-one that the formula invites.

Shortcut. Find the last value: the largest 5 + 7k not above 50 is 47, at k = 6, so k runs 0 to 6, which is seven passes.

Common trap. 6 comes from dividing the range 45 by the step 7 and dropping the +1 for the starting value i = 5.

A loop that steps by seven — Pseudocode Aptitude Question

A loop that steps by seven: How many times does the body of the loop execute? Answer and worked solution on CodeKairo.

Question

How many times does the body of the loop execute?

Integer i, c
Set c = 0
For i = 5 to 50 step 7
    Set c = c + 1
End For
Print c

Options

  1. 6
  2. 7
  3. 8
  4. 9
Show the answer and the worked solution

Correct answer: B. 7

Worked solution

  1. i takes the values 5, 12, 19, 26, 33, 40 and 47.
  2. The next value would be 54, which is above 50, so the loop stops.
  3. That is 7 executions of the body, so 7 is printed.

Answer: 7.

The idea

For a loop from a to b with step s the count is floor((b − a) / s) + 1. Listing the values is quicker under exam pressure and immune to the off-by-one that the formula invites.

Shortcut. Find the last value: the largest 5 + 7k not above 50 is 47, at k = 6, so k runs 0 to 6, which is seven passes.

Common trap. 6 comes from dividing the range 45 by the step 7 and dropping the +1 for the starting value i = 5.

All Pseudocode questions · placement mock tests