Tracing the AND code click by click
Here is the click code of switch A. If its text is Off, it becomes On, and then an inner If checks the other switch: the lamp is lit only if B is On too. Otherwise, when A was On, it becomes Off and the lamp is unlit, because one open switch breaks AND. The code of switch B is its mirror image, with A and B swapped. Notice that when A turns On while B is Off the lamp does not need changing: it was unlit already, because A was Off. The nested If is the AND: the outer test says A is being switched On, and the inner test says B is On. To trace the code, write a table with one row per click, showing the texts of A and B and the lamp after the click. The first row is the start state.
| Step | Click | A | B | Lamp |
|---|---|---|---|---|
| 0 | (start) | Off | Off | unlit |
| 1 | A | On | Off | unlit |
| 2 | B | On | On | lit |
1Private Sub SwitchA_Click(sender As Object, e As EventArgs) Handles SwitchA.Click 2 If SwitchA.Text = "Off" Then 3 SwitchA.Text = "On" 4 If SwitchB.Text = "On" Then 5 ShowLamp(True) 6 End If 7 Else 8 SwitchA.Text = "Off" 9 ShowLamp(False) 10 End If 11End Sub
| Step | Click | A | B | Lamp |
|---|---|---|---|---|
| 0 | (start) | Off | Off | unlit |
| 1 | A | On | Off | unlit |
| 2 | B | On | On | lit |
| 3 | A | Off | On | unlit |
| 4 | B | Off | Off | unlit |
| 5 | B | Off | On | unlit |
| 6 | A | On | On | lit |
1Private Sub SwitchA_Click(sender As Object, e As EventArgs) Handles SwitchA.Click 2 If SwitchA.Text = "Off" Then 3 SwitchA.Text = "On" 4 ShowLamp(True) 5 Else 6 SwitchA.Text = "Off" 7 ShowLamp(False) 8 End If 9End Sub
On Off -> lit
Trace the correct code on paper from the start state for the clicks B, A, A, B. Write a table with one row per click and the texts of A and B and the lamp after it.