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

~90s

Read, transform, print

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 If
Show the answer and the worked solution

Correct answer: C.

14

Worked solution

  1. Set a = a + b makes a = 6 + 14 = 20.
  2. Set b = a - b makes b = 20 - 14 = 6, which is the original a.
  3. a = 20 is greater than b = 6, so the program prints a - b = 20 - 6 = 14.
  4. 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.

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.

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 If

Options

  1. 6
  2. 8
  3. 14
  4. 20
Show the answer and the worked solution

Correct answer: C. 14

Worked solution

  1. Set a = a + b makes a = 6 + 14 = 20.
  2. Set b = a - b makes b = 20 - 14 = 6, which is the original a.
  3. a = 20 is greater than b = 6, so the program prints a - b = 20 - 6 = 14.
  4. 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.

All Pseudocode questions · placement mock tests