PPA - TRO F05D Unit 2 (Scratch Part 2) FINAL
PPA - TRO F05D Unit 2 (Scratch Part 2) FINAL
Unit 2
Basic programs in Scratch
DEVELOPED: 2019-2021
Reflection............................................................................................................................................................................................................. 62
Sources consulted ................................................................................................................................................................................................. 63
You OWN your learning – therefore you need to reflect on your learning process. At the end of each lesson, you need
to have a discussion with yourself and/or fellow students and/or lecturer to reflect on the lesson of the day. See the
paragraph called ‘Reflection’ at the end of the chapter for examples of questions you can include in your discussions.
Unit 2: Basic programs in Scratch
Assessment criteria
The content covered in this unit relates to the following outcomes and assessment criteria:
Assessment Criteria
• Redundant information can be excluded from a basic programming problem statement by rewriting the problem without redundant information.
• Missing data can be identified in a basic programming problem statement, by listing the missing data elements.
• Problems requiring logical thought flow can be analysed and solutions provided by providing narratives, diagrams or completing tables.
Outcome: The student must be able to apply algorithmic problem solving to basic mathematical and programming problems.
Assessment Criteria
In Unit 1 you created a program (a small game) where the user had to try to click on a moving sprite (the Ball sprite). When the user managed to click
on the ball, it changed position, and a sound was played (Boing).
Now we would like to improve on this game, so that we can keep score of the number of times the ball has been hit. This is
what we will need to do:
• Create a ‘container’ where the computer can put the score to ‘remember’ the number of hits (a variable).
• When the program starts, we have to place the value 0 (zero) in the container, to indicate that no hits have yet been
made.
• Every time the ball is hit, we instruct the computer to increase the value in the container by one.
In programming languages, this ‘container’ for a value is called a variable. A variable has a name and can hold only one • Variable
data item (for example a number, or a name) at a time. In the following activity we will show you how to add a variable to
the existing program to count the number of hits.
• Initialise
• Assignment
statement
To create the instruction to increase the variable iHits by 1, look at the colours of the blocks to determine from which class to obtain
the separate blocks. Add them in the scripts area.
Remember
• Programming variables are given meaningful names. You can name a variable x, or y. But in longer programs with many variables you will
become confused if you only use single-letter variable names. In programming we use meaningful variable names such as iNumStudents,
iTestTotal, iScore instead of x, y and z.
• An integer is a number that is not a fraction, a whole number, such as 10; 25; 166.
• In programming languages values that have a decimal point in them, such as 12.8; 145.07823; 0.678 are called floating point numbers. They can
also be called real numbers, measuring numbers or measurement numbers. In programming languages it is important to note that the value 5 is
an integer, but the value 5.0 is a decimal (real) value.
• When we name variables in a program, it helps to include a reference to the type of number that will be stored in a variable. For example, iHits
indicates that an integer value will be stored in the the variable. rAvg indicates that a real number will be stored in the variable.
Here are examples of other algebra equations and their corresponding Scratch assignment statements:
𝑠𝑐𝑜𝑟𝑒
𝑎𝑣𝑔 = ∗ 100
𝑡𝑒𝑠𝑡𝑇𝑜𝑡𝑎𝑙
𝑝𝑜𝑖𝑛𝑡𝑠 = 𝑝𝑜𝑖𝑛𝑡𝑠 + 25
Helpful hints:
• Create a variable for each sprite. Choose the option For this sprite only. The variables for the different sprites can have the same name (iVote).
The readouts on the stage includes the names of the sprites, so it is clear to see whose variable each value belongs to.
• Add instructions for each sprite to initialise the variables to 0 when the green flag is clicked.
Note
• In Activity 2 you used two sprites, and each had one variable. Each had control over their own variable.
Worked example: Use variables visible to the stage and all sprites
• Create a program containing two sprites – the letter I and the letter O.
The difference between For all sprites and For this sprite only • Banner
• Prop
For this sprite only For all sprites
The objects used on a
Only the sprite can access the value of the variable. All sprites on the stage have acces to the variable. stage or screen by actors
when they perform is
The variable has sprite scope. The variable has stage scope. called theatrical property.
This has been shortened
Similar to an actor who can only read the words on his Similar to an actor that can see all banners or props
to ‘props’. So a prop
own script, not that of another actor. that is placed on the stage.
refers to anything
The readout on the stage displays the name of the The readout on the stage only displays the name and movable or portable on a
sprite before the name and value of the variable. vlaue of the variable. stage.
• Stage scope
• Sprite scope.
In the next Activity you will use 4 sprites, and 1 variable. Each sprite must have access to the variable.
Examples of the assignment statements you will use are: This variable has stage scope. Therefore no
iFoodScore = iFoodScore + 10 name of a sprite is displayed infront of the
readout. All sprites have access to the same
iFoodScore = iFoodScore - 12 variable.
The only difference between this program and the previous ones are that you have more sprites, and that the variable is not just increased or
decreased by 1.
This program let the sprite jump up and down the screen 3 times. Now we want to change the program so it will ask the user how many times the
sprite should jump up and down. The user will type a value on the keyboard, and push the <Enter> key. The program will then use the value
entered by the user in the [repeat] block. When values are provided by the user on the keyboard, it is called input to the program. (A value is placed
IN to the program).
ask "How many times should I jump? " The [ask] block (in the Sensing group)
prompts the user to enter the data requested
by the programmer using the keyboard.
display "Hello!"
In pseudocode and most programming languages' code, double quotes are used to indicate that a value is a string, for example, "Hallo!" is a string.
These are more examples of strings:
"I am dancing"
"This is gr8!"
"PO Box 58234"
You can combine blocks to create output using a [join] block from the operators class. The [join] block has two
editboxes where you can enter sentences or variable names to display.
These are examples of using [say], [join] and other blocks to create output:
You can use multiple [join] blocks to concatenate (add together) different components to form one output message.
iAge = 8
display "I am " + iAge + " years old"
The + symbol indicates that different components must be joined to form the output. These components are:
Display output
Add code to the program Unit 2 JUMP so the sprite will display a message to report how many times it
jumped. For example:
If you do not leave any spaces in the output strings, the output will ook like this:
Look at the following algorithm in pseudocode and the corresponding Scratch code.
• Interface
Writing basic programs • Comparisons
The programs we have written up till now have been very plain, designed to introduce you to the Scratch interface and • Retrieve
basic programming language terminology. However, the actual usefulness of computers lies in their ability to perform
calculations and process data quickly and accurately. The aim of learning to program is learning how to instruct the
computer to process data and perform calculations.
Before attempting to write code to solve problems, we need to understand how computers work. In short, computers
receive input, process the input and give output.
Values entered by the user of the program. Results / answers displayed by the computer.
• receive input (from various sources, e.g. keyboard, mouse, storage media)
• perform calculations (usually mathematical in nature)
• make comparisons (and then perform certain actions as a result of this)
• give output (to various devices such as the screen, storage media, printer)
• store and retrieve data
• So the first thing we have to learn in programming is to identify input and output, and decide on the processing that will be needed. We will now
show you some examples on how to plan and write programs which involve calculations.
Step 2: What values do you know that will not Step 4: If you assume you know the input Step 1: What do you need to calculate and/or
change during the program? value(s), how will you calculate the answer? display?
Step 3: What data values do you need? Let us pretend the input value number of tickets
bought is 3. Then we would calculate the total
The name of the student. as:
An assignment statement. Assign the Now you can translate the mathematical
value calculated on the right-hand side calculation to an assignment statement sName (The name of the student.)
of the = sign to the variable on the left (a formula):
rTotal (The total cost of the tickets.)
Write an algorithm for the program. The string created using the [join] blocks will be displayed in
the speech bubble close to the sprite. You can also use the
The complete algorithm in pseudocode is as follows:
readouts for variables to display the values.
when the user clicks the green flag
Constant
ONETICKET = 200
ask "What is your name? " You need to display the letter R in front of the amount, so
enter sName that the person who uses the program can see the amount
ask "How many tickets do you want to buy? " Input is a currency in Rand.
enter iNumTickets
Content of variable
The output is made up of three parts, so you rTotalCost
need to use two [join] blocks.
It is good practice to use capital letters only for the name of values that will not change during the run of the program. For example, in the program
calculating the cost of the ticket, it will stay R200 per person. If you want to change the value to R250, you can see easily where the fixed values
(constants) in your program is when you use capital letters in the names.
Cost of tickets
Watch the video to see how to create the output using the say and join blocks, then write the program to calculate the
cost of all tickets in Scratch.
Step 2: What values do you know that will Step 4: If you assume you know the input value(s), Step 1: What do you need to calculate
not change during the program? how will you calculate the answer? and/or display?
There are no fixed values Let us pretend the student scored 45 out of 60. Then The percentage for the test.
we would calculate the percentage as follows:
Step 3: What data values do you need?
45/60*100 = 75
The score of the student.
You can write it as a formula:
The total of the test.
Score of the student (iScore) rPercentage = iScore/iTestTotal * 100 The percentage of the test (rPercentage)
3 + 4 * 5 means 3 + (4 * 5) = 3 + 20 = 23.
Parentheses ()
Most programming languages have built-in ‘knowledge’ of the order of precedence in Exponents ^
calculations; for example, multiplication and division are performed before addition and Multiply Divide MOD (* / \ %)
(operator on left side first)
Add Subtract (+ -)
(operator on left side first)
Unit 2 : Basic programs in Scratch 26
3 + 8 + 12/4 = 3 + 8 + 3 = 14
When you want addition or subtraction to happen first in a calculation, you need to use
parentheses to ensure that is does happen first. For example, when calculating the average
of three numbers, it should be done as follows::
When writing a program, the programmer has to apply mathematical principles correctly when programming calculations – such as using parentheses
– the programming language has no way of ‘knowing’ that parentheses should have been used to calculate the average. It only performs the
instruction as it was provided.
In Scratch, the effect of parentheses and the order of precedence in calculations is achieved by stacking various program blocks from the Operators
group. In other programming language the calculations are typed on one line, and the language will automatically do the calculations in the correct way
(following rules for order of operations.
1. The multiplication has to be completed first. So drag a multiplication block from the
Operators class to the scripst area, and enter the values 4 and 5.
2. Drag an addition block onto the scripts area. Enter the value 3.
3. Now plug the multiplication operator into the open slot on the right side of the addition
Notice how the multiplication block appears to be raised higher. It is at the top of the stack.
Scratch will perform the calculation at the top of the stack (i.e. the multiplication) first.
Here are more examples of the way stacking should be used to ensure the correct order of precedence:
12 ÷ 6 ÷ 2 12 ÷ (6 ÷ 2)
12⁄ 12
6
= 2 =6
⁄2
= 12/6/2
= 12/(6/2)
This should be programmed as (12/6)/2, since the rules for the order of precedence)
indicate that division is carried out from left to right.
12 ÷ 2 x 2 12 ÷ (2 x 2)
12
=
12
𝑥2 =
2∗2
2
= 12 / (2 * 2)
= 12 / 2 * 2
1. Add 5 to 20.
2. You scored 45 out of 60 for a test. Calculate your percentage.
3. Calculate the average of the three numbers 68, 89 and 77.
4. Calculate (3 + 2) / (1 + 1).
5. Determine the speed of a car that travels 14 km in 8 minutes, in km/h.
6. Increase the value of 100 by 15%.
7. Calculate 15% of 100.
8. Decrease the value of 100 by 15%.
If you want to test a calculation quickly, you do not need to write a complete program using a sprite and program blocks. You can use a mathematical
operator block only, enter values in the slots, and left-click on the block. A speech bubble
will appear containing the answer
Read the amount a customer spent at the bookshop. The program must calculate and display the amount of VAT the customer should pay, as well as
the total amount (original + VAT) to be paid.
Step 2: What values do you know that will Step 4: If you assume you know the input value(s), Step 1: What do you need to calculate
not change during the program? how will you calculate the answer? and/or display?
VAT is 15% of the amount spent. Let us pretend the customer spent R245. The amount VAT to be paid.
Step 3: What data values do you need? Calculate the amount VAT The total to be paid..
rVAT =
rTotalToPay =
NOTE
Test data: Use the following values to test your program. • Every time you run the program, you can use a different value
for the amount spent. That is why the input and output values
rSpent rVat rTotalPay
are called variables.
100 15 115 • You should not program the values of the test data e.g. 100 or
250.88 in the code of the program.
250.88 37.632 288.512
All decimal values will be displayed, not just 2 as we would prefer when displaying a monetary value. • Monetary value
You will learn how to display only 2 decimal values for values when you program in Java.
C:\Users\wassermannu\AppData\Local\Programs\Scratch Desktop"
Create an IPO-table, then complete the algorithm and write a Scratch program to implement the algorithm.
Create an IPO-table, then complete the algorithm and write a Scratch program to implement the algorithm.
Calculate age this year
Ask the user for the current year and the user’s year of birth, and then calculate and tell the user how old he or she will be in the current year.
Create an IPO-table, then complete the algorithm and write a Scratch program to implement the algorithm.
Calculate perimeter and area
A builder wants to calculate the perimeter and surface area of the floor of a room. Applying your knowledge of Mathematics, you know that the length
and width of a rectangular area are needed to calculate the area and perimeter. The table below shows the input and output required as well as the
processing of the data.
The length of the room (rLength) rPerimeter = 2 x rLength + 2* rWidth The perimeter (rPerimeter)
The width of the room (rWidth) rArea = rLength *rWidth The area (rArea)
Write an algorithm to obtain data, perform calculations and display the output.
There are more types of data, and we will learn to use them later in this module.
Monetary values always have a decimal value – even if the amount is R 5.00 and the decimal part of the value is 0, you will want to display 2
decimal values, e.g. R5.00, or R6.70. Note: The ‘R’ character is not part of the value the variable contains. As the programmer you always
have to display the letter ‘R’ in output values in Scratch.
• The first character of a variable name should be an alphabetical character (not a number or symbol), and should be an indication of the type of
value that will be stored in the variable. For example: iCount (an integer value), rAverage (a real value), sName (a string).
• Do not use spaces in variable names. For example, instead of ‘Term Mark’, rather use the name TermMark or Term_Mark.
• The name of the variable should describe its content. For example sName or iCount or iMark.
• Use a capital letter for the first character of each word that make up the variable name, e.g. sCellNumber, sDateOfBirth.
Variable names
Indicate whether the following variable names are good choices or not. Provide a reason when it is not a good choice, and provide a better alternative.
a) iPhoneNumber
b) sISBN
c) sUrnames
d) rNum2
e) sSum
f) sName&Surname
g) Endangered species
h) rTo
i) rAmountPayable
j) tShops
k) 18holeCourseName
Do the calculation using a pocket calculator and writing down all the Refer to your calculations, and complete the following algorithm:
calculations.
when the user clicks on the green flag
ask "How far is your room from the campus (in m)? "
enter rDist
ask "How many days do you walk to campus? "
enter numDays
Use the following test data to determine whether your program is correct.
500 2 2
850 5 8.5
1300 4 10.4
Library fine
A library charges a fine of 50c per day per book if a book is returned late.
A student has 4 books and hand them in 5 A student has 9 books and hand them in 4 days late. Write a formula in pseudocode to calculate the
days late. How much is the fine (in Rand)? How much is the fine (in Rand)? fine if x books are y days late.
Write an algorithm using valid variable names to read the number of books and the number of days they have been returned late, then calculate and
display the fine in Rand.
Cross multiply (we do not use variables such as x and y, rather variable names that describes the
rCandyWeight rAmount unknown value).
Develop an algortihm to read the weight of the candy bought, then calcuate and display the amount to be paid. Candyweight Amount
Write a Scratch program to implement the algorithm. 350 R22.75
Use the test data provided to test your program. 120 R7.80
Apple profit
A bag with 10 apples costs R30. If you sell each apple for R5, how much profit will you make? (Do the calculation here.)
A bag with 22 apples costs R50. If you sell each apple for R1.50, how much profit will you make? (Do the calculation here.)
Create an algorithm in pseudo code so a program will read how many apples are in a bag, what is the cost of the bag, how much will you charge for
one apple. The program should calculate and display the total amount of profit when all the apples are sold.
The first three minutes of a phone call costs 50c per minute. The remaining minutes (everything more than 3 minutes), costs 15c per minute. Write a
program to calculate the total cost of a phone call when the duration of the call is provided. Assume the user will never enter a value less than 3.
You can draw a diagram such as the following one to indicate how the price of a phone call will be calculated.
Step 2: What values must you use? Step 1: What do you need to calculate
and/or display? (Output)
First 3 minutes cost 50c per minute
The total cost of the phone call.
Remaining minutes cost 15c per minute.
Step 3: What information do you need? Step 4: If you use a test value, how will you calculate
(Input) the answer?
rFirstCost = 3 * 0.5
iRemMin =
rCostRem =
rTotalCost =
Write an algorithm for the program.
// Input
ask "What is the duration of the call? "
enter iDuration
// Processing
// Output
display
end
Translate the algorithm to programming code.
The way the output is displayed, is not really effective, since each value is displayed for only 2 seconds, then it • List
disappears. It would be better to use a structure where all the output lines will be visible. In Scratch we can use a • String
structure called a List. It can be found in the Variables class. A List is one structure that consists of many lines –
each line contains one value. When we use a List as ouput structure, each line will contain a string. The output on
the screen will look as follows:
The [delete all of] block removes all lines in the List. Therefore when the
program is executed a second time, the previous output will be deleted.
rLength
Sometimes you will receive an example of the output of a program. You can use this output to
help you to plan your program. Highlight rWidth all the values in the output where variables will
have to be used. rArea
In the screenshot alongside, you can see rPerimeter which values are obtained from variables.
Real values (also called floating point values), are not stored with complete accuracy. For example, the vaue 0.5 is • Floating point values
stored as 0.5000000000000001. Therefore, when real values are displayed, the programming language approximate
the values. However, the developers of Scratch did not build this functionality into Scratch when displaying values to
a List. When you program in Java, you will learn how to prevent this type of display issue.
Remember to plan
• Draw a diagram to represent the way the salary will be calculated.
• Indicate the variables in the examples of output.
• Determine the output and input variables, and use any number (e.g. 12) as input.
• Complete the calculation yourself. Ensure you are able to do the calculations correctly by comparing your answer to the test data provided. Write
a complete algorithm, then write the Scratch code.
In other programming languages, you indicate fixed values by using special key
words, and the programming language will not allow you to make changes to these
values. The values are then called constants.
The kennel also charges 25% of the total kennel fee to exercise the dogs each day. The owner should pay
separately for food for the dog charged at a fee per day. Calculate and display the kennel and exercise fees, as
well as the cost for the food. (All dogs will stay for at least two days.)
An example of output is provided. Use the output to determine which values to calculate and
display.
Write a Scratch program based on the pseudocode.
Sell magwinya
Pulani made bakes magwinya to sell to fellow students. The muffins she does not sell, she gives away to students in need (so she does not receive
money for them). She wants a program to calculate her profit per day.
The following values are constants: The following values should be entered for a specific day:
• The cost price to bake one dozen. • The number of dozens of magwinya she baked.
• The price of one magwinya. • The number of magwinya she sold.
when the user clicks the green flag
// Declare fixed values Calculate and display:
COSTDOZEN = 32
COSTONE = 3.5 • how much money she needed to bake the magwinya,
• what percentage of magwinya did she sell,
• how much money she received from her sales, and
• how much profit she made.
We have 13 sweets, and need to divide it How will we calculate the number of sweets each
equally between 4 children. How many sweets child should receive for any number of sweets, and
wil each child receive? We need to use integer any number of children?
division.
Use the following variables:
13 \ 4 = 3
iNumsweets; iNumChildren; iNumEach
(3 * 4 = 12, so you can give each child 3 iNumEach = iNumSweets \ iNumChildren
sweets) or
We can also use the floor notation to indicate 𝑖𝑁𝑢𝑚𝐸𝑎𝑐ℎ = ⌊𝑖𝑁𝑢𝑚𝑆𝑤𝑒𝑒𝑡𝑠⁄𝑖𝑁𝑢𝑚𝐶ℎ𝑖𝑙𝑑𝑟𝑒𝑛⌋
that a value should be ‘rounded down’, or we
can say the fraction part of the number should
be removed (truncated).
13
⌊ ⌋
4
We have 13 sweets, and need to divide it How will we calculate the number of sweets that will
equally between 4 children. How many sweets remain for any number of sweets, and any number of
will be left over after each child received the children?
same number of sweets? We need to use the
Use the following variables:
modulus operator (MOD).
iNumsweets; iNumChildren; iNumLeft
Joseph wants to paint his mother’s house and How will we calculate the number of containers for Programming languages have methods
calculated that he needs 164 litres of paint. any number of litres paint, and any size container. available to ‘round a value up’. In
However, the paint is only sold in 20 litre Use the following variables: Scratch we have the ceiling method.
containers. How many containers of paint must
iLitrePaint ; iInContainer; iNumContainers
he buy?
iNumcontainers = ⌈iLitrePaint⁄iInContainer⌉
164/20 = 8.2 – therefore we need to buy 9
containers. The value 8.2 must be ‘rounded up’
to 9.
In Mathematics we can use the ceiling notation
to indicate that a value should be rounded up.
164
⌈ ⌉
20
Example 1
15 ÷ 6 = 2 remainder 3
15 = 6 * 2 + 3
15 \ 6 = 2 15 MOD 6 = 3
(The integer part of the division) (The remainder after long division)
On your pocket
calculator the result of
the division will be 2.5.
The result of integer
division is the number
before the decimal point. Just ignore the
fraction.
Example 2
5÷7 = 0 remainder 5
5=7* 0 + 5
5\7= 0 5 MOD 7 = 5
134 = 7 * _____ + _____ 134 ÷7 = _____ remainder _____ 134 \ 7 134 MOD 7 =
12 = 2.5 * _____ + _____ 12 ÷ 2.5 = _____ remainder _____ 12 \ 2.5 = 12 MOD 2.5 =
Write an algorithm to solve the problem, then write a Scratch program based on the algorithm.
• this time we are going to ask the user what amount the customer pays after displaying the amount,
• then calculate and display the amount of change to be returned to the customer.
Write an algorithm for the program.
• Read the number of items a customer buys and the price of one item. (All items have the same
price.)
• Display the cost of all the items, and ask the user what percentage discount must be given.
• Display the discount amoount, as well as the final amount to be paid.
An example of output is provided. Use the output to determine which values to calculate and display.
Write a Scratch program based on the pseudocode.
An example of output is provided. Use the output to determine which values to calculate and display.
Write a Scratch program based on the pseudocode.
Knowledge questions
a) What is a variable?
b) What is the difference between a radiobutton and a checkbox?
c) How can a readout be used to help you to find errors in your program?
Skills checklist
Ensure you can do the following:
I know how ✓
l) Apply the rules of the order of processing by using stacking of code blocks in Scratch.
n) Write programming solutions where more data must be obtained after output has been
displayed by the program.
(Sackson, 2011)