← All questions
RareComputer science

What is the final value of b after the four assignments?

Short answer
48

Exercise

a := 10
a := a + 2
b := a + a / 2
b := a + b * 2

Solution

a = 10 + 2 = 12

b = 12 + 12/2 = 18

b = 12 + 18 × 2 = 48

The right-hand side of an assignment uses the values available before that assignment. After line two, a is twelve and stays that way. Line three produces eighteen. The last line reads that old b, doubles it, adds a, and replaces b with the result.

(a, b): (10, —) → (12, —) → (12, 18) → (12, 48). 48 − 12 = 36; 36/2 = 18.

Trace the instructions in order. A test reads the current values, an assignment replaces a value, and output uses the value present when execution reaches it. Recording each new state makes the result checkable.

Algorithms

Platforms

  • MAXIMUM

Download now and try it for free on your own tasks!

10 15 free credits • No credit card required
Version: Loading…

Choose the Windows app or the Chrome extension with phone controls.