Understanding the Mathematical Order of Precedence

As is the case with all programming languages, Scratch allows you to string together different combinations of numbers code blocks in order to create more complicated numeric calculations. For example, take a look at the following script.

Here, a small script has been created that evaluates a numeric expression and assigns the result to a variable named Total. This equation was created by embedding a series of numbers code blocks within one another. Specifically, the equation was created by embedding the code blocks shown in Figure 8.2 into one another.

Figure 8.2. Creating complex formulas by assembling different combinations of code blocks.


As shown in Figure 8.2, the equation was assembled by embedding the division code block into a variable block. Next, the addition code block was embedded within the left-hand side of the division code block. Finally, a multiplication code block and a subtraction code block are embedded within the input fields of the addition code block.

Like all programming languages, Scratch evaluates the components of mathematical expressions by following a specific order, referred to as the order of precedence. Specifically, Scratch evaluates an expression using a top-down approach. When applied to the example shown in Figures 8.2, Scratch evaluates it as follows:

  1. First, it calculates the value of the two top code blocks. Therefore, 4 is multiplied by 5, yielding a value of 20, and 2 is subtracted from 4, yielding a value of 2. At this stage, the expression has been evaluated as shown here.

    20 + 2 / 2
  2. Next, the expression located in the second level code bock (the addition block) is evaluated. Therefore, 20 is added to 2, yielding a value of 22. At this stage, the expression has been evaluated as shown here.

    22 / 2
  3. Finally, the lowest level code block is evaluated, dividing 22 by 2 and resulting in a final value of 11.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.187.233