Pseudocode Drills

tags: - cocubes - pseudocode - practice


Pseudocode Drills

Set a 15-minute timer. Show your variable table on rough paper before checking answers.

Questions

1. Even sum

SET s = 0
FOR i = 1 TO 6
  IF i MOD 2 = 0 THEN
    SET s = s + i
  END IF
END FOR
DISPLAY s

2. Number reversal

SET n = 420
SET r = 0
WHILE n > 0
  SET r = r * 10 + (n MOD 10)
  SET n = n DIV 10
END WHILE
DISPLAY r

3. Value swap

SET a = 5, b = 2
SET a = a + b
SET b = a - b
SET a = a - b
DISPLAY a, b

4. Powers

SET a = 3, b = 4, result = 1
WHILE b > 0
  SET result = result * a
  SET b = b - 1
END WHILE
DISPLAY result

5. Nested IF

SET x = 5, y = 8, z = 3
IF x > y THEN
  DISPLAY 1
ELSE
  IF y > z THEN
    DISPLAY 2
  ELSE
    DISPLAY 3
  END IF
END IF

6. Recursion

FUNCTION G(n)
  IF n <= 1 THEN
    RETURN 1
  ELSE
    RETURN n * G(n - 1)
  END IF
END FUNCTION
DISPLAY G(4)

7. Counting

SET c = 0
FOR i = 10 TO 16
  IF i MOD 3 = 1 THEN
    SET c = c + 1
  END IF
END FOR
DISPLAY c

8. Repeat-until

SET x = 1
REPEAT
  SET x = x * 2
UNTIL x >= 10
DISPLAY x

9. Complexity

FOR i = 1 TO n
  SET j = 1
  WHILE j <= n
    SET j = j * 2
  END WHILE
END FOR

10. Fibonacci-style update

SET f = 0, g = 1
FOR i = 1 TO 4
  DISPLAY f
  SET f = f + g
  SET g = f + g
END FOR

Answers

    1. Add 2+4+6.
    1. Leading zero disappears in an integer.
  1. 2, 5.
  2. 81.
  3. 2.
  4. 24.
    1. Values are 10, 13, 16.
    1. The body runs before the condition check.
  5. O(n log n).
  6. 0, 1, 3, 8.

For every error, write the cause in [[10_Templates/Error_Log|Error log]]: update order, loop semantics, condition, integer division, recursion, or complexity.