Introduction to App Inventor Programming
Introduction to App Inventor Programming
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-3
THE MOST IMPORTANT LESSON OF THE ENTIRE COURSE
The Most Important Lesson of the Entire Course
The process of writing a program can be viewed as a form of “teaching.” Whenever you write any computer
program, you are, in a sense, “teaching” a computer how to solve a particular problem. KEEP IN MIND THAT
YOU CANNOT “TEACH” A COMPUTER TO SOLVE A PROBLEM THAT YOU DO NOT KNOW HOW TO SOLVE!
BEFORE YOU EVEN ATTEMPT TO WRITE CODE (PROGRAMMING INSTRUCTIONS), FIRST YOU MUST DEVISE A STRATEGY!
BEFORE YOU CAN DEVISE A STRATEGY, YOU MUST ENSURE THAT YOU UNDERSTAND THE PROBLEM! THE FOLLOWING
TABLE DESCRIBES A SOUND APPROACH TO SOFTWARE DEVELOPMENT. IF YOU HOPE TO BE SUCCESSFUL, FOLLOW THE
GUIDELINES IN THE SECOND AND THIRD COLUMNS. DO NOT FOLLOW THE STEPS IN THE FIRST COLUMN!
Input Output ?
1. Read
2. Choose a 2. You may design an interface for your program at this stage but you MUST NOT
problem
strategy write any code yet! In addition, it is important to consider a variety of algorithms.
(Design) Break up the large problem into several smaller sub-problems. Choose algorithms
that best balance user ease, execution speed, programming complexity (ease of
2. Type implementation) and storage requirements.
code 3. Carry out the 3. At this stage, you write code but NOT all in one fell swoop. Write code for one
strategy sub-problem at a time. Do not integrate a solution to a sub-problem into the larger
(Implementation) solution until you are confident that it is correct. It is also wise to save each
version of your program. In case of a catastrophe, you can always go back to an
3. Run the earlier version.
program
4. Check the 4. Extensive testing should take place to find bugs that were not noticed in the
solution implementation phase. It is best to allow the testing to be done by average
(Validation) computer users who are not programmers. Because of their computer expertise,
programmers unconsciously tend to avoid actions that cause computer programs to
fail. Once the software is released, additional bug fixes will usually be necessary
as users report previously undiscovered bugs. This is known as the maintenance
phase.
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-4
What is a Program? What is a Programming Language?
Important Terminology
Program
A program is a sequence of instructions that a computer can interpret and execute. (“Execute” means “carry
out” in this context.)
Programming Language
A programming language is a very precise and unambiguous language that is designed to allow
instructions to be given to a computer.
Code
Programming instructions are often called “code.” Programmers say that they are “writing code” when they
write programs.
Bug
A fault or defect in a computer program, system, or machine. Bugs are usually due to design flaws.
Algorithm
An algorithm is a systematic procedure (finite series of steps) by which a problem is solved. Long division is
an example.
The steps of a particular algorithm remain the same whether you solve a problem by hand or by computer.
In cooking, algorithms are called recipes.
Algorithms have been worked out for a wide range of problems.
For many problems, there exist many different algorithms.
For some problems, there are no known efficient algorithms (too slow and/or require too much memory).
e.g. What are the prime factors of a number?
Some problems cannot be solved by a computer (i.e. no algorithm exists that can be implemented on a
computer).
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-5
LEARNING THE ESSENTIAL FEATURES OF APP INVENTOR
Brief Description and History of App Inventor for Android
Allows anyone to create software applications (“apps”) for the Android Operating System
The Android Operating System is used on several different mobile devices including models made by
Samsung, HTC, LG, Motorola, Sony, Alcatel, Archos, Kyocera, Dell, Xperia, Excite, Asus, Sanyo, Acer, etc
Originally provided by Google and called “Google App Inventor”
Google terminated support for App Inventor on December 31, 2011 but donated the project to MIT
Since then, the application has been maintained by MIT (Massachusetts Institute of Technology)
Now called “MIT App Inventor 2” (original version now called “MIT App Inventor Classic”)
App Inventor
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-6
The MyProjects Page
List of Properties
Used to Select
of the
Components for
Component
the User
Selected in the
Interface
Components List
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-7
PAINTPOT: CREATING YOUR FIRST APP
Step 1: Creating the PaintPot App
This part is easy! All you need to do is follow the instructions on the following Web page:
[Link]
If you follow the instructions very carefully, the app should function correctly. In the event that it does not
work as expected, check your blocks carefully to ensure that they are exactly as shown in the above document.
Step 2: Using the Cook/Chef Analogy to Understand the Logic of the PaintPot App
As can easily be appreciated from the above analogy, it is not enough merely to follow existing programs. All
programmers must also be able to develop new software from scratch. To accomplish this, it is obviously very
important to understand programming concepts. A detailed description of the programming concepts used in
PaintPot is given below.
Picture Programming Concepts
Variable
Name of Value of
Variable Variable A variable is a name that is used to represent a value that is
stored in a computer’s main memory (i.e. in the RAM).
Variables are used whenever information needs to be
“remembered” (i.e. “memorized”) for later use.
The concept of variable in computer science is similar but not
identical to the concept of variable in mathematics.
One key difference is that in mathematics, variable names must
have a length of exactly one character. For example, the variable
(a) In the first example, the variable name “x” is allowed but the variable name “xavier” is not allowed
“dotSize” is created and given an
initial (starting) value of 10.
because it would be interpreted as “x times a times v times i times
(b) In the second example, the value of
e times r.”
“dotSize” is changed. Its value is In computer science, variable names can contain more than one
set to the same value as that of the character because the multiplication operator (*) cannot be
variable “thumbPosition.”
omitted. Thus, the name “xavier” would be seen as a single
(c) The modifier “global” means that entity and not a series of multiplications.
the variable is can be accessed and
changed by any procedure. In In most cases, variable names in programming should contain
addition, the value of the variable more than one character because descriptive names make
will remain stored in memory for as programs far easier to understand. For example, “dotSize” is far
long as the app is running.
more meaningful than “x,” “y” or “d.”
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-8
Picture Programming Concepts
Procedure (aka Subprogram, Subroutine)
Name of Name of the Event Name of a In App Inventor, a procedure is used to group
Component that causes execution Property of a together one or more instructions.
(aka Object) of procedure block Component Each procedure has a unique name.
Some procedures are executed automatically when a
specific event occurs. These are called event-
handling procedures or just event handlers.
Other procedures are executed in response to a
specific instruction called a “call” of the procedure.
Event
An event is an occurrence that takes place while a
program is running. Events are used to trigger the
Procedure. The instructions within Value of the execution of specific instructions.
the block are executed when the “PaintColor” Examples of events include “Click,” “LongClick,”
“Click” event occurs on “RedButton.” Property “GotFocus,” “LostFocus,” “Dragged” and
“Touched.”
Property
Every component has
Properties, which
store information on
characteristics of the
Name of Name of the Event The Parameters of the component.
Name of a
Component that causes execution “[Link]”
(aka Object) of the procedure
Method A property can be
procedure block. These are
considered a variable
special variables that are used
that belongs to a
to pass information to the
procedure block. In this component.
example, the parameters x and Examples of
y store the co-ordinates of the properties include
point that is touched on “Height,” “Text” and
“DrawingCanvas.” The “Width.”
parameter “touchedSprite” is
used for animations. Method
Every component has
Methods, which are
The Arguments passed to the actions that are
“DrawCircle” method. The associated with the
values of x and y come from component.
Procedure Block with Parameters the parameters x and y of the
The instructions within the block are executed when the procedure block A method can be
“Touched” event occurs on “DrawingCanvas.” The “[Link].” considered a
parameters of this procedure block are the variables x, y The radius of the circle comes procedure that
and touchedSprite. from the value of “dotSize.” belongs to a
component.
Examples of methods
include
“DrawCircle,” and
“DrawLine.”
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-9
Exercises
Study the following diagram. Then answer the questions found below the diagram.
7. The names “x,” “y,” “touchedSprite,” “startX” and “startY” are all examples of ______________________.
These are used to _______________________________________________________________________ .
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-10
SOME IMPORTANT NOTES ON MEANING!
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-11
CREATING MORE APPS – MORE EXAMPLES
Resources
1. App Inventor 2 Course-In-A-Box: [Link]
2. App Inventor 2 Book: [Link]
3. S:\OUT\Nolfi\ICS3U0\00-AppInventor\0. App Inventor 2 Files
Warning!
By following the instructions in the resources listed above, you will be able to
create many impressive and interesting apps. However, you must always keep
in mind that the ultimate objective is to UNDERSTAND PROGRAMMING
CONCEPTS. This means that you must THINK CRITICALLY AS YOU
WORK. Once you develop a sufficient understanding of the concepts, you will
be well on your way to developing your own apps and more importantly, you
will be well on your way to being able to
THINK FOR YOURSELF!
1. Levels of Difficulty: “Easy,” “Medium,” “Difficult” (e.g. the game can be made more challenging by
increasing mole speed, decreasing size of the mole picture, etc)
2. A pleasant sound is played when the mole is hit.
3. The mole picture changes briefly when the mole is hit.
4. A rude sound is played when the mole is missed.
5. The game ends after a certain number of hits and misses, after which the player is declared either a
winner or a loser.
6. To begin the game, the player enters his/her name.
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-12
7. A “bonus image” is occasionally displayed for a brief time. Bonus points are awarded for tapping the
bonus image.
8. A “penalty image” moves about the canvas in proximity to the mole image. If the player taps the
penalty image instead of the mole, the player loses points.
9. List any other improvements you can think of in the space provided below:
Upcoming Assignment
Very soon, you will create your first app that is to be submitted to the teacher for evaluation.
At this stage, you should begin collecting ideas. Keep a record of ALL your ideas, regardless of how crazy you
might think they are. When the time comes to develop your app, you can select your most realistic ideas and
save the others for future projects.
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-13
UNDERSTANDING MOLEMASH
The Co-Ordinate System of a Canvas
x-axis
The diagram at the right shows the co-ordinate system used in the
MoleMash game. Notice the following features of the co-ordinate system: The mole’s
co-
A. The origin is at the top-left corner of the canvas. ordinates
correspond
B. The x-axis is horizontal. to the
image
C. The y-axis is vertical but upside-down. sprite’s
top-left
corner.
Questions
Refer to the diagram at the right whenever necessary.
1. Fill in the blanks. Your goal is to understand the logic and the meaning y-axis
of the given blocks.
(c) The special variables “x” and “y” are called ____________________ . They represent the ___ and ___
co-ordinates of the top-left corner of the _______________ image sprite. Both of these variables are
given random integer values. Explain the following:
Why is “x” given a random integer value ranging from 0 to [Link] – [Link]?
___________________________________________________________________________________
___________________________________________________________________________________
Why is “y” given a random integer value ranging from 0 to [Link] – [Link]?
___________________________________________________________________________________
___________________________________________________________________________________
2. The “MoleMash” app uses a “clock” component. Explain in detail how this component works and its
specific purpose in the “MoleMash” app.
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-14
USING “MOLEMASHIMPROVED” TO REVIEW APP INVENTOR MAIN IDEAS
Upload “MoleMashImproved” from “S:\OUT\Nolfi\ICS3U0\00-AppInventor\0. App Inventor 2 Files” to
your “My Projects” page.
After testing “MoleMashImproved” and studying its blocks carefully, answer the following questions:
(b) List all the component names in the blocks shown at the left.
(c) List all the event names in the blocks shown at the left.
(d) List all the property names in the blocks shown at the left.
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-15
2. Explain Purpose
(a) What are “x,” “y” and “touchedAnySprite?” What is their purpose? Be specific!
(b) Explain the purpose of the “if” block as well as the “not” and “and” blocks. Again, be specific!
3. Explain Concepts
(a) Explain why it makes sense to create a procedure like “MoveMole” rather than copying and pasting
instructions.
(b) How many times is “MoveMole” called in “MoleMashImproved?” Explain the purpose of these calls.
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-16
REVIEW: EXPLAIN APP INVENTOR MAIN IDEAS
1. Component
2. Property
3. Method
4. Event
5. Procedure
6. Event Handler
7. Click Event
8. Initialize Event
9. Timer Event
11. Variable
12. Call
13. Parameter/Argument
14. if block
15. Image
16. Sprite
18. Canvas
Procedures
(aka "Subroutines" and
"Subprograms)
Programmer-
Built-in (Intrinsic)
Event Handlers Methods Defined
Procedures Procedures
Examples
Event Handlers Methods
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-18
Advantages of Programmer-Defined Procedures
Eliminate repetitive code by encapsulating (i.e. enclosing) the solution to a problem in a procedure.
The program is more concise and better organized, making it much easier to understand.
Debugging is much easier because bugs are localized to a particular procedure.
Making changes is much easier because modifications only need to be made within a particular
procedure.
Well-designed procedures can be reused in other programs. (The problem is solved once and for all!)
Examples
1. Write a procedure that disables all the sprites in the “SplitterBust” game.
2. Write a procedure (with a result) that calculates the length of a line segment given the co-ordinates of its
endpoints.
C A2 B 2
Local Variables
Should be used whenever possible
Exist only within the procedure in which they are
A defined and only while the procedure is being
B executed
Only use memory (RAM) while procedure is running
Cannot cause bugs in other procedures
A2 B 2
A2 B 2
Return (“Output”) the Result
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-19
Exercises
1. Write a procedure with a result that takes the endpoints of a line segment as inputs and returns
(i.e “outputs”) the midpoint of the line segment. Hint: Use a list to store the co-ordinates of the midpoint.
2. Write a procedure with a result that takes the coefficients of a quadratic function f x ax 2 bx c as
inputs and returns (i.e “outputs”) the roots (solutions) of the quadratic equation ax 2 bx c 0 .
Hint: Use a list to store the roots of the quadratic equation.
Challenge: Return the roots even when there are no real roots. Use i to represent 1 .
Theory
b b 2 4ac
The quadratic formula x is the general solution of the quadratic equation
2a
ax 2 bx c 0 .
Examples
5 52 4 1 6
1. x 5 x 6 0
2
x x 2 or x 3 (two real roots)
2 1
2 2 4 11
2
2. x 2 x 1 0
2
x x 2 (one real root)
2 1
4 42 4 1 5 4 4 4 2 1 4 2 1
3. x 4 x 5 0
2
x 2 1
2 1 2 2 2 2
In this case there are no real roots but there are two complex roots: x 2 i , x 2 i
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-20
GENUINE PROBLEM SOLVING
SPLITTERBUST: A VARIATION OF MOLEMASH/MILEYBASH
the game ends and the user loses the game. In this case, Mr. T’s
picture appears and the line, “I pity the fool who messes with the
splitters!” is played over the speakers.
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-21
Clock
Properties: TimerEnabled, TimerInterval, TimerAlwaysFires
Methods: SystemTime, Now, MakeInstant, MakeInstantFromMillis, GetMillis, … (too many to list)
Events: Timer
References
[Link]
[Link]
2.
3.
4.
5.
6.
7.
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-22
APP INVENTOR: REVIEW OF MAIN IDEAS
Complete the following table. Please ensure that your responses are brief, to the point and accurate.
Variable
Global
Local
Parameter
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-23
Concept Appearance/Examples of Use Explanation
Address the following in your answer:
purpose of procedures, purpose of parameters, how an
event handler differs from other procedures, how a
method differs from other procedures, how a programmer-
defined procedure differs from a built-in procedure,
meaning of call
Procedure
Event Handler
Method
Programmer-
defined (with
and without
result)
Built-in
Function/Proc-
edure
Conditional
If…Then
If…Then
Else
If…Then
ElseIf … Then
ElseIf … Then
…
Else
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-24
Concept Appearance/Examples of Use Explanation
Address the following in your answer:
How does a computer generate random numbers? Are
these numbers truly random? What is the difference
between “/” and “quotient?” On what type of data can
mathematical operations be applied?
Math Operations
+, −, *, /, ^
Random
Numbers
Rounding
Quotient and
Remainder
Types of Data
Numeric
Text (“String”)
Logical
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-25
Concept Appearance/Examples of Use Explanation
Address the following in your answer:
Why would you use a list? What does a list allow you to do?
List
Create list
Add item to list
Delete from list
Select item from
list
Search for an
item in a list
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-26
INTRODUCTION TO LOOPS: LINE DRAWING PROBLEMS
Introduction
Although we most definitely perceive a curve in the picture at
the right, the picture itself was created by drawing only a
series of straight lines. No curves were actually drawn! Why
then do we seem to see a curve? The answer to this question
has everything to do with how our brains construct the
“reality” that we “see.” Since every straight line in this
diagram is tangent to the curve that we “see,” our brains take
all the points of tangency and “connect” them to create the
perception of a curve.
Problem
Use App Inventor to create an app that can generate the
diagram at the right.
Hints
1. Use a “Canvas” component.
2. In addition, your app will need to use the “DrawLine” method of a “Canvas” component.
3. You need to understand the co-ordinate system that is used for “Canvas” components.
4. There is a definite pattern that governs how the lines are drawn. Before attempting to create blocks for your
app, you must figure out the pattern!
Explanation
The main idea behind reproducing pictures like the one given above is to use the idea of “reverse engineering.”
That is, we try to “take apart” the picture to understand how it was created in the first place.
For convenience, the canvas size is set to 300 pixels by 300 pixels. This not only fits nicely on most cell phone
screens but it also takes advantage of the fact that the number 300 has many divisors (i.e. 1, 2, 3, 4, 5, 6, 10, 12,
15, 20, 25, 30, 50, 60, 75, 100, 150, 300).
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-27
Generating the Pictures in App Inventor
Method 1- Easy to Understand but Tedious Method 2 – Harder to Understand but much more Efficient
Summary
Counted Loops (“For Loops”)
These are used when the number of repetitions is known at design-time (i.e. while the program is being
designed) or can be calculated at run-time (i.e. when the program is running). Whether looping continues or
terminates is based on a count. The number of repetitions of such loops is always predictable.
Analogy: Add three teaspoons of sugar to the coffee. Repeat the act of adding one teaspoon of sugar 3 times.
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-28
Problems
Use graph paper and a table of values to determine the pattern that is used to create each picture. Then create
App Inventor apps that generate each of the following pictures. Your app must be able to draw the picture all at
once and in an animated way (i.e. one line at a time)
1. 2. 3.
4. 5. 6.
7. 8. 9.
13. 14.
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-29
LINE DRAWING CHALLENGE – THE PLACEMAT SPIRAL
Challenge
Create an App Inventor app that generates the following picture (often called a “placemat spiral”) using nothing
but straight lines!
Hints
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-30
CIRCLE DRAWINGS
Exercises
Create App Inventor apps that generate each of the following pictures. Your app must be able to draw the
picture all at once and in an animated way (i.e. one circle at a time)
Co-ordinates of
Centre of Circle
Radius of Circle
1. 2. 3. 4.
5. 6. 7. 8.
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-31
GPA: APP INVENTOR CHALLENGE PROBLEM
1. Most high schools in the United States, as well as almost all universities in North America, use a grading
system known as the grade point system. In the grade point system, letter grades (i.e. A, B, C, etc.) are
replaced with numeric values. This allows an average, known as the grade point average or GPA, to be
computed. The actual scale used for grade point averaging purposes varies from jurisdiction to jurisdiction
and from institution to institution. The one shown below is used at the University of Toronto.
Create an App Inventor app that allows the user to enter any number of percentage grades. After the user
clicks “Submit,” the app displays the user’s GPA as well as his/her percentage average.
Hints
1. Create a programmer-defined procedure like
the one shown at the right.
2. Use an “if” statement within the procedure
that has a structure like the one shown at the
right.
3. Use lists to “remember” the courses and
marks entered by the user.
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-32
PROGRAMMING PROBLEMS WHOSE SOLUTIONS REQUIRE THE USE OF
COUNTED (“FOR”) OR CONDITIONAL (“WHILE”) LOOPS
Algorithm
An algorithm is a systematic procedure by which a problem is solved. Long division is an example.
In cooking/baking/mixing drinks etc, algorithms are called recipes.
Many of the problems given below can be solved using an exhaustive search (aka brute-force search)
algorithm. An algorithm that employs an exhaustive search systematically checks all possible candidates for
the solution to see which of them, if any, satisfies the statement of the problem.
Exhaustive search is guaranteed to find a solution if one exists. However, when the number of possible
candidates is very large, brute-force methods are excruciatingly slow. Shortly, we’ll be investigating a better
solution to (g) to help us understand the limitations of brute-force algorithms.
Complete the following table. Then write App Inventor programs to solve each problem.
Can you write a solution that only
Programming Problem
requires a counted loop? Explain.
(a) Write a program to calculate the sum of all positive even integers Yes / No (Circle One)
less than or equal to 1000. Why?
(b) Write a program to calculate the sum of all positive odd integers Yes / No (Circle One)
until the sum exceeds 1000. Why?
(c) Write a program to calculate the product of all positive integers Yes / No (Circle One)
divisible by 5 and less than or equal to 645. (What happens if Why?
you try a value ≥ 650?)
(d) Write a program to calculate the product of all positive integers Yes / No (Circle One)
divisible by 5 while the product is less than or equal to 1000000. Why?
(e) An integer is called prime if it has exactly two divisors, one and Yes / No (Circle One)
itself. The following is a list of the first 10 prime numbers: 2, 3, Why?
5, 7, 11, 13, 17, 19, 23, 29
Write a program that determines whether a given number is
prime. (Exhaustive Search)
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-33
Can you write a solution that only
Programming Problem
requires a counted loop? Explain.
(f) A proper divisor of an integer is any integer that divides evenly Yes / No (Circle One)
into the integer, except for the number itself. For example, the Why?
proper divisors of 12 are 1, 2, 3, 4 and 6. A number is called
perfect if the sum of its proper divisors is equal to the number
itself. Two examples of perfect numbers are 6 and 28 because
6 = 1 + 2 +3 and
28 = 1 + 2 + 4 + 7 + 14.
Write a program that determines whether a given number is
perfect. (Exhaustive Search)
(g) Write a program that finds the greatest common divisor of any Yes / No (Circle One)
two integers. For example, the greatest common divisor (GCD) Why?
of 24 and 40 is 8. (Exhaustive Search)
(h) Write a program that finds the least common multiple of any Yes / No (Circle One)
two integers. For example, the least common multiple (LCM) Why?
of 24 and 40 is 120. (Exhaustive Search)
(i) The numbers 220 and 284 are called an amicable pair because Yes / No (Circle One)
the sum of the proper divisors of 220 is 284 and the sum of the Why?
proper divisors of 284 is 220. Write a program that finds all
amicable pairs within the search range 1 ≤ x ≤ 1000000.
(Exhaustive Search)
(j) Horses cost $10, pigs cost $3 and rabbits cost only $0.50. A Yes / No (Circle One)
farmer buys 100 animals for $100. How many of each animal Why?
did he buy? Write a program to search for the solution to this
problem. (Exhaustive Search)
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-34
EUCLID AND THE GCD
Definition of gcd
The Greatest Common Divisor (gcd) of two positive integers is the largest integer that divides both integers
exactly.
Examples
gcd 8,12 4 because 4 is the largest integer that divides into both 8 and 12
gcd 14, 42 14 because 14 is the largest integer that divides into both 14 and 42
gcd 9, 28 1 because 1 is the largest integer that divides into both 9 and 28
Brute Force (Exhaustive Search) Algorithm for Computing the GCD of Two Integers
The most obvious method for computing the gcd of two integers is to perform an exhaustive search of the set of
all possible divisors. The search may not find any divisors other than one or it may find several divisors. In
either case, the gcd must be the largest divisor found. This is illustrated below.
a, b: These variables store the two integers for which the gcd must be found. The values of these two
variables do not change throughout the execution of the code.
y: This variable stores the values of all the integers that we try to divide into both a and b. The value
of this variable is controlled by a “for each” loop.
gcd: This variable stores the greatest common divisor found so far. Before entering the loop, it is
initialized to 1 because 1 divides into every number. If no other common divisor is found by the “for each”
loop, the value of ‘gcd’ never changes, meaning that its final value will be 1 (see the second table).
Remainder obtained when Remainder obtained when
a b y gcd
‘a’ is divided by ‘y’ ‘b’ is divided by ‘y’
Values Before
Entering Loop 8 12 ? ? ? 1
8 12 2 0 0 2
8 12 3 2 0 2
8 12 4 0 0 4
8 12 5 3 2 4
8 12 6 2 0 4
8 12 7 1 5 4
Values After 8 12 8 0 4 4
Exiting Loop 8 12 9 1 3 4
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-35
App Inventor Code for “Brute Force” GCD Algorithm
The following is a procedure that calculates and displays the GCD of the integers “x” and “y.” Study the code
and then answer the questions found below.
Questions
1. Explain the purpose of the “if” statement that immediately precedes the “for each” loop.
2. Why does the search for common divisors end at the smaller of “x” and “y?”
3. The greatest common divisor of 1,000,000,000 and 500,000,000 is 500,000,000. How many times do the
instructions within the “for each” loop need to be repeated before the procedure finds this answer?
Comment on the efficiency of using an exhaustive search to compute the gcd of a pair of very large
numbers. Can you think of any ways of improving the efficiency of the process?
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-36
Description of Euclid’s (Fast) Method for Computing the GCD of Two Integers
Background
More than 2000 years ago, Euclid published an algorithm for finding the GCD of two numbers. His version
was strictly geometric since algebra had not been invented yet, but the algebraic version is described below.
Summary
The Euclid algorithm can be expressed concisely by the following recursive formula:
gcd(a, b) = gcd(b, a mod b)
Note: a mod b means the remainder obtained when a is divided by b.
Example
Here is an example of Euclid’s algorithm in action.
Find the GCD of 2322 and 654. Essentially, the Euclidean algorithm
a b performs the following two steps:
gcd(2322, 654) = gcd(654, 2322 mod 654) = gcd(654, 360)
2322 654
gcd(654, 360) = gcd(360, 654 mod 360) = gcd(360, 294) 1. The value of ‘b’ is copied to ‘a.’
654 360
gcd(360, 294) = gcd(294, 360 mod 294) = gcd(294, 66) 2. The value of ‘b’ changes to the
360 294
gcd(294, 66) = gcd(66, 294 mod 66) = gcd(66, 30) value of ‘a mod b” (the original
294 66
gcd(66, 30) = gcd(30, 66 mod 30) = gcd(30, 6) value of ‘a’ must be used,
66 30 i.e. the value of ‘a’ before step 1
gcd(30, 6) = gcd(6, 30 mod 6) = gcd(6, 0)
30 6 was carried out).
gcd(6, 0) = 6
6 0
Therefore, gcd(2322,654) = 6. This process continues until the
value of ‘b’ is zero.
Your Task
1. Use Euclid’s method to 2. How many repetitions would be required by the “slow GCD” algorithm
calculate gcd(4896, 830). to compute gcd(4896, 830)?
a b
Enrichment Questions
1. Who was Euclid? Why do historians of mathematics consider him an extremely important figure?
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-37
SOLUTIONS TO SELECTED PROBLEMS REQUIRING LOOPS
Problem App Inventor Solution Notes
(a) Write a The procedure “addUpIntegers” Values of variables
can find the sum of any number sum
program to arithmetic series (within the before entering loop
calculate the numeric range available in App
− 0
2 2
{
Inventor). Arithmetic series
sum of all take the following form: Values of variables
4 6
positive even
a a d a 2d after each repetition
integers less of the loop 6 12
than or equal
a nd 8 20
to 1000. The series 2+4+6++1000 is
Values of variables . .
an example of an arithmetic . .
series. after exiting loop . .
998 249500
1000 250500
− 250500
Think of this algorithm as the
“cash register algorithm.”
Values are successively added to
the total until the final total is
obtained. For this problem, a
“for” loop can be used because
the number of repetitions is
known at design-time.
(b) Write a Unlike “for each” loops, “while” loops do not have a
program to The solution to this problem also
built-in loop counter variable. However, it’s a very
calculate the makes use of the cash register
simple matter to include a variable that behaves just
algorithm.
sum of all like a loop counter.
positive odd x sum
integers until −1 0
the sum 1 1
exceeds 1000. 3 4
5 9
7 16
. .
. .
. .
61 961
63 1024
− 1024
However, this time a “for” loop
cannot be used because the
number of repetitions is not
known at design-time. The
instructions within the body of
the loop are repeated as long as
the sum remains smaller than or
equal to 1000.
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-38
Problem App Inventor Solution Notes
divisor gcd
- 1
(g) Write a program 2 2
that finds the 3 2
greatest 4
4
common divisor
5 4
of any two
integers. For 6 4
See page 36. 7 4
example, the
greatest common 8 4
divisor (gcd) of 9 4
24 and 40 is 8. 10 4
(Exhaustive 11 4
Search) 12 4
− 4
The final value of the
variable “gcd” turns out to
be 4. Therefore,
gcd(12, 20) = 4.
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-39
Problem App Inventor Solution The outer loop controls the
value of the ‘horses’ variable.
This solution involves a “while” With each repetition of the
loop contained within another outer loop, the value of
“while” loop. When one loop is ‘horses’ increases by 1.
contained within another, we The values of the ‘pigs’
say that the loops are nested. variable must be reset to
zero before the inner loop is
executed. What goes
wrong if this is not done?
Keep in mind that this procedure has a major bug. If a solution exists, this procedure
will find it. However, if there is no solution, an erroneous result will be produced.
In class, you were asked to correct this bug.
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-40
First Repetition of Outer Loop Second Repetition of Outer Loop
Inner Loop Repeats 17 Times Inner Loop Repeats 13 Times
horses pigs rabbits cost horses pigs rabbits cost
1 1 98 $62.00 2 1 97 $71.50
1 2 97 $64.50 2 2 96 $74.00
1 3 96 $67.00 2 3 95 $76.50
1 4 95 $69.50 2 4 94 $79.00
1 5 94 $72.00 2 5 93 $81.50
1 6 93 $74.50 2 6 92 $84.00
1 7 92 $77.00 2 7 91 $86.50
1 8 91 $79.50 2 8 90 $89.00
1 9 90 $82.00 2 9 89 $91.50
1 10 89 $84.50 2 10 88 $94.00
1 11 88 $87.00 2 11 87 $96.50
1 12 87 $89.50 2 12 86 $99.00
1 13 86 $92.00 2 13 85 $101.50
1 14 85 $94.50
1 15 84 $97.00
1 16 83 $99.50
1 17 82 $102.00
Third Repetition of Outer Loop Fourth Repetition of Outer Loop
Inner Loop Repeats 9 Times Inner Loop Repeats 5 Times
horses pigs rabbits cost horses pigs rabbits cost
3 1 96 $81.00 4 1 95 $90.50
3 2 95 $83.50 4 2 94 $93.00
3 3 94 $86.00 4 3 93 $95.50
3 4 93 $88.50 4 4 92 $98.00
3 5 92 $91.00 4 5 91 $100.50
3 6 91 $93.50
3 7 90 $96.00
3 8 89 $98.50
3 9 88 $101.00
Fifth Repetition of Outer Loop
Inner Loop Repeats 1 Time
horses pigs rabbits cost
5 1 94 $100.00
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-41
Questions
1. What is the purpose of the variable ‘copyOfY’ in the Euclidean GCD program? What would go wrong
without this variable?
2. Explain how the brute force GCD program could be made more efficient. Would these gains of efficiency
make a significant difference when computing the GCD of very large numbers?
3. What is a loop counter variable? Explain how to implement a loop counter in a “while” loop.
4. In the “Horses, Pigs, Rabbits” program, what will go wrong if the value of the variable ‘pigs’ is not reset to
zero just before the inner loop is executed?
5. Write an App Inventor program that uses the Sieve of Eratosthenes algorithm to generate a list of all prime
numbers less than 400.
Please note! You will need to do some research to solve this problem! For starters, visit the following Web
page:
[Link]
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-42
APP INVENTOR REVIEW PROBLEMS #1
1. Give a step-by-step explanation of how the
following could be accomplished:
A variation of the MoleMash game replaces the
picture of the mole with pictures of members of
the Split Personalities. Each time a picture of
one of the splitters is tapped, the member’s
favourite rap line is heard over the speakers and
displayed in a label. Otherwise, if the user taps YouTube Poppa
the screen without hitting any of the moving Junkie Rabid Addy Cricket
images, Mr. T’s picture appears, and the line “I JiveMan Manic
pity the fool” is played over the speakers.
Mono Jazzy
Tune Street
SPLIT
2. Create an App Inventor program that calculates the sum shown below, where the values of x, d, k and n are
chosen by the user.
n
x k x d x 2d x n 1 d x i 1 d
k k k
i 1
For example, if the user chooses x = 3, d = 2, k = 4 and n = 10, then the program would compute the sum
34 54 7 4 94 214 . You should create a procedure with a result that is devoted to calculating the
sum.
3. Create an App Inventor program just like the one in question 2 except that the user specifies the maximum
(or minimum) sum instead of specifying the number of terms (i.e. instead of n).
4. Create an App Inventor program that can add, subtract multiply or divide any two fractions.
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-43
APP INVENTOR REVIEW PROBLEMS #2
1. Give a step-by-step explanation of how the
following could be accomplished:
A variation of the MoleMash game replaces the
picture of the mole with pictures of members of
the Split Personalities.
Each time a picture of one of the splitters is
tapped, the picture disappears but reappears
exactly one minute later. YouTube Poppa
Junkie Rabid Addy Cricket
If the user is fast enough to make all the JiveMan Manic
pictures disappear before any of them
reappear, the game ends and the user wins. Mono Jazzy
Tune
If any of the pictures are still in motion after Street
2. Create an App Inventor procedure with a result that takes a percentage mark as input and returns the
equivalent grade point score. (See page 32 for details.)
3. Create an App Inventor program that factors quadratic expressions. The app takes as input the coefficients
a, b and c of the quadratic in standard form (i.e. ax 2 bx c ) and then displays the factored form of the
quadratic.
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-44
APP INVENTOR REVIEW PROBLEMS #3
Write an App Inventor program that can produce string art. Examples of string art are shown below:
Note
The prefix “pseudo” means “false.”
Other words beginning with this prefix:
pseudonym, pseudoscience, pseudohistorical
The co-ordinates of the points spaced uniformly around the perimeter of the polygon (e.g. octagon) can be
generated mathematically. Once generated, the co-ordinates can be stored in lists.
Copyright ©, Nick E. Nolfi ICS3U0 Introduction to Programming through App Inventor IPAI-45
Using local variables within procedures is a best practice because they exist only during the procedure's execution, reducing memory usage and preventing potential bugs outside of the procedure scope . In App Inventor, this ensures that memory is efficiently used, and local variables do not interfere with other procedures, resulting in more reliable and maintainable code .
Programmer-defined procedures in App Inventor are significant because they encapsulate repetitive code, making applications more concise and better organized, enhancing readability and understanding . This practice facilitates easier debugging by localizing bugs to specific procedures and simplifies modifications since changes only need to be made within those procedures. Furthermore, well-designed procedures can be reused across different programs, promoting code reuse and saving development time .
The cook/chef analogy illustrates the difference between merely following instructions (like a cook) and understanding how to create new solutions (like a chef). For beginners in App Inventor, this analogy emphasizes the importance of not only following tutorials but also comprehending the underlying programming concepts to enable independent problem-solving and the creation of original applications . It fosters a deeper understanding and encourages learners to transition from replicating existing solutions to innovating their own.
In computer science, unlike in mathematics, variable names can have more than one character because multiplication operators cannot be omitted, allowing for descriptive naming conventions that enhance code readability. Descriptive variable names like 'dotSize' are preferred over single-character names because they make programs easier to understand by providing context and meaning, which is critical when programs become complex .
Counted loops simplify repetitive tasks in App Inventor by allowing a fixed number of repetitions, which is ideal for tasks like generating a series of lines in graphical projects. For example, the 'for each' loop efficiently repeats the 'DrawLine' method a specified number of times, reducing the complexity of manually coding each line draw operation and ensuring consistent execution of tasks . This leads to more organized and readable code while achieving the desired graphical output.
Exhaustive search algorithms, like those used for identifying amicable pairs, involve evaluating all possible candidates, which can become computationally expensive and time-consuming as problem size increases. These algorithms lack efficiency due to their brute force nature and often become impractical for large datasets. Despite their simplicity, exhaustive searches do not scale well, requiring optimizations or alternative algorithms for more complex problems to achieve timely results .
The Euclidean algorithm is significantly more efficient than brute force methods for computing the GCD. While brute force involves testing all possible divisors, the Euclidean algorithm reduces the problem size rapidly by using modulo operations, leading to faster convergence to the GCD with fewer steps . This efficiency is particularly evident when dealing with large numbers, where brute force could be computationally expensive.
Loops in App Inventor, such as 'for' loops and 'while' loops, are crucial for implementing iterative processes. The choice between these depends on whether the number of iterations is known at design-time or determined dynamically. 'For' loops are appropriate when the iteration count is predetermined, optimizing performance by reducing overhead. Conversely, 'while' loops excel in cases where iterations depend on runtime conditions, providing flexibility but potentially increasing computational load if not efficiently managed .
Understanding the coordinate system in App Inventor's Canvas is crucial because it allows developers to precisely place graphical elements like lines and shapes. By knowing how coordinates function, developers can implement drawing patterns accurately. For instance, in the creation of a diagram that appears curved using straight lines, understanding the points of tangency and coordinate positions is essential for visually accurate results . This knowledge is foundational for creating dynamic graphical applications where precision is key.
Reverse engineering is valuable in App Inventor projects as it helps developers deconstruct graphical representations to understand the underlying patterns and methods used to create them. This approach enables developers to replicate or enhance existing designs by learning how specific elements interact on the Canvas, leading to more efficient and innovative solutions . It allows for the extraction of design principles and establishes a base for further customization and application development.