Read, transform, print — Pseudocode Aptitude Question
Read, transform, print: The program is run with the inputs a = 6 and b = 14, in that order. What is printed? Answer and worked solution on CodeKairo.
- Topic: Pseudocode
- Section: Programming MCQs
- Difficulty: Medium
- Time target: 90 seconds
Question
The program is run with the inputs a = 6 and b = 14, in that order. What is printed?
Read Integer a
Read Integer b
Set a = a + b
Set b = a - b
If a > b Then
Print a - b
Else
Print b - a
End IfOptions
- 6
- 8
- 14
- 20
Show the answer and the worked solution
Correct answer: C. 14
Worked solution
- Set a = a + b makes a = 6 + 14 = 20.
- Set b = a - b makes b = 20 - 14 = 6, which is the original a.
- a = 20 is greater than b = 6, so the program prints a - b = 20 - 6 = 14.
- That is the value b started with.
Answer: 14.
The idea
Half of the additive swap idiom leaves a as the sum and b as the original first input, so the printed difference is the original second input. Recognising the idiom removes the need to guess which branch runs.
Shortcut. Both branches print the absolute difference |a − b|, so no branch needs deciding: after the two assignments a = 20 and b = 6, and |20 − 6| = 14.
Common trap. 8 is 14 − 6, the difference of the raw inputs; it skips the two assignments that turn a into the sum 20 and b into 6.