C3.2 Read and alter existing code, including code that involves conditional statements and other control structures, and describe how changes to the code affect the outcomes

Skill: Reading Code


Reading code involves interpreting blocks or commands to make predictions about its outcome. Reading code is also an important part of debugging to identify and correct errors of why the code is not working or getting the desired outcome.

For example, when the student encounters a conditional statement while reading code, he or she must interpret this as a contingency in the code that underlies an action. There is then more than one possibility related to the execution of the code. In cases of more complex code, it may be beneficial to combine reading code with writing a flowchart to ensure a clear understanding of what is being read.

Skill: Altering Code


One of the reasons to alter code is to save time by not starting from scratch but to use existing code to build something new. Altering code can also be done to make the code more efficient and reduce runtime or to demonstrate that there is more than on way to use code to represent a situation. Another reason to alter code is to fix errors and make it functional, a process called debugging.

For example, the student could start with a code that makes a sprite move around the screen. The student's job would be to create interactive elements when the sprite comes into contact with other objects. Here is an example of a possible interaction:

Skill: Describing the Impact of Altering Code


Understanding the sequencing of events that will occur based on the code is important for altering code so that one can make predictions about how the changes will affect the outcome.

For example, it is possible to represent a situation in which the theoretical probability of getting "heads" or "tails" by tossing a coin would be determined.

In this context, there are two possibilities, either "heads" or "tails". These two possibilities can be associated with two numbers, 1 and 2, and generate random results that are then compiled into an array. The pseudocode might look like this:

Variables

Battery (set to 0)

Face (set to 0)

Throws

Result

Ask "how many pitches do you want to generate?"

Throws = Response

Repeat ("Throws") times

Set "Throws" to (random number between 1 and 2)

If "Answer" = 2

Then add 1 to Tails

Otherwise

Add 1 to Face

Following the reading of this pseudocode, the student could be asked questions such as:

  • What if, instead of 1 and 2, the result options were 2 and 4?
  • How could I use two "if-then" commands instead of one "if-then-else" command?
  • What would be the impact of removing the "set to 0" commands at the beginning of the code?