Coding For Parents: Multiplication

Teach Your Child About Multiplication

I got two boys who is in the age were you start learning the basics of numbers and arithmetic. I’ve want to talk about how I’ve created simple programs to help them practice using numbers. Contrary to popular belief, programming is something everybody can learn to do. You don’t need a 3 year university education in software development to create the sort of programs I will show you here.

My program for practicing addition, multiplication and subtraction, looks like this:

It is a text based program using the programming language Julia. That is why the prompt says julia>. To learn how to install Julia and get it running, you can have a look at one of my Julia introduction videos.

Creating Random Numbers

The program works by repeatedly asking the user to give the answer the multiplication of two random numbers. We use rand() to create a random number in Julia.

julia> rand()
0.8579770262264026

However we don’t want to multiply numbers with lots of decimals. We want whole numbers (integers) to multiple. Fortunately we can do that.

julia> rand(3:6)
3

julia> rand(3:6)
4

This creates random numbers in a range you specify. From 3 to 6 in this case. The ranges you specify are inclusive. That means they include both the starting number and ending number. If you write e.g. 7:16 that would mean a number from 7 to 16 including both 7 and 16.

Asking User To Answer Question

We can create two random numbers we call a and b and ask the user to calculate them.

a = rand(1:10)
b = rand(1:10)

To show the question to the user we write:

print(a, "*", b, " = ")

We need to place this code into a file e.g. named aritmetic-practice.jl. It is convention to give files with Julia code the name ending .jl. The text needs to be in plain text such as UTF8. You can do that by using special programmer's editors such as:

  • Atom. Quite promising and extensible editor, with good Julia integration through the Juno package. My only issue with this is rather limited UI, and sucking up a lot of resources.
  • Sublime
  • Textmate, which is my personal favorite, although it is receiving a lot less attention these days.
  • Vim, old school text editor, with a mainly text based interface. Advance but not well suited for beginners.

After you save the file, you can run the code in the file by writing at the command line:

$ julia aritmetic-practice.jl 
9*8 = ⏎

Notice you only actually write julia aritmetic-practice.jl and hit enter. I write $ and julia> to help you see which program you are entering commands in.

The print() function is used to display text strings on the screen. It can also convert other data types such as numbers to text. Here are some examples.

Print a single string:

julia> print("hello world")
hello world

Multiple strings:

julia> print("hello", "world")
helloworld

Combining string literals, variables and numbers:

julia> name = "Joe"
"Joe"

julia> age = 50
50

julia> print(name, " are you really ", age, "?")
Joe are you really 50?

Reading Reply

Of course not much point in asking a question if you can’t get an answer. You can read from files such our code file aritmetic-practice.jl with the readline() function.

julia> readline("aritmetic-practice.jl")
"a = rand(1:10)"

But we don’t want to read from a file, but rather what the user writes on the keyboard. Fortunately as a heritage from Unix systems, the keyboard is treated as just another file. In Julia this file is called STDIN.

julia> readline(STDIN)

Then I just write something say:

hello world

And the readline() function returns what I wrote:

"hello world"

Checking if Reply is Correct

Once we got a reply from the user, we have to check if it is correct or not to be able to tell the user and e.g. update his/her score.

c = readline(STDIN)
if a*b == c
println("Correct!")
else
println("Wrong")
end

What you see here is an example of what we call the if-statement. We use it to compare things, such as numbers. The comparison we perform a*b == c is called the condition. If the condition is true, we will run all the code between if and else, if there is an else present, otherwise the code between if and end.

We then update our whole julia aritmetic-practice.jl source code file to contain:

a = rand(1:10)
b = rand(1:10)
print(a, "*", b, " = ")
c = readline(STDIN)
if a*b == c
println("Correct!")
else
println(a, "*", b, " = ", a*b, " Wrong")
end

Debugging

However you will notice, that “Wrong” is printed out regardless of what you write. We’ll have to debug this code and find out what is wrong. In Julia a bit primitive but easy way of doing this is by pasting individual lines of code in your program in to check if they do what is expected.

julia> a = rand(1:10)
7

julia> b = rand(1:10)
6

julia> a*b
42

julia> c = readline(STDIN)
42
"42"

Then we can check the condition of the if-statement.

julia> a*b == c
false

Hmm… this doesn’t make sense. Lets check more thoroughly:

julia> a*b == 42
true

julia> c == 42
false

julia> c
"42"

julia> 42 == "42"
false

Do you see the problem? Julia distinguishes between the number 42 and the text string 42. We need to turn the text into a number. We use the parse() function to turn text into other types of objects.

julia> parse("42")
42

So we got to change this line of code:

c = readline(STDIN)

Into:

c = parse(readline(STDIN))

Now I can run this and it works:

$ julia aritmetic-practice.jl 
2*3 = 6
Correct!

Repeatedly Asking Questions

Of course the program is rather useless at the moment as it can only ask the user for the correct answer once. What we need is a way of repeating the same code multiple times. We need what is called a loop construct. In Julia we got two for-loops and while-loops. I will start with the for-loop.

We do this by putting all our previous code between a for i in 1:4 line at the beginning and end to mark the end of the block of code we want to repeat multiple times.

for i in 1:4
a = rand(1:10)
b = rand(1:10)
print(a, "*", b, " = ")
c = parse(readline(STDIN))
if a*b == c
println("Correct!")
else
println(a, "*", b, " = ", a*b, " Wrong")
end
end

You can run this with $ julia aritmetic-practice.jl and see that you get asked to answer four times. The way this works is that variable i is given the values from 1 to 4 (1:4) on each iteration of the code inside the for loop. Often we would use this variable, but we are not going to do that in this instance.

Keep Track of the Score

If we ask a lot of questions, it is useful to keep track of the number of correct answers.

We’ll keep track of the score in a variable called score. Each time we got a correct answer we add 1 to it. We can write that as:

score = score + 1

But in most programming languages we have a short cut for modifying a variable:

score += 1

So lets change our program to keep track of score. You’ll notice I am using n to keep track of number of questions, since we need to know this when telling the user how many correct answers they got out of the total number of questions.

n = 4   # number of questions
score = 0
for i in 1:n
a = rand(1:10)
b = rand(1:10)
print(a, "*", b, " = ")
c = parse(readline(STDIN))
if a*b == c
println("Correct!")
score += 1
else
println(a, "*", b, " = ", a*b, " Wrong")
end
end
println("Score $score/$n")

In the last line, we use something called string interpolation to put the values of variables score and n into the text string.

Writing Text in Color

You’ll notice in the picture of my original program you can see colors.

For that I am using the function print_with_color() like this:

print_with_color(:red, " Wrong\n")
print_with_color(:green, "Correct!\n")

The \n at the end of each text string means a new line. Usually I use println() instead of print() when I want a new line, but that is not an option in this case.

Colors are indicated with names such as :blue:cyan:green and :light_black. You might wonder why the colon in front? Just like strings are encapsulated with quotation marks ", symbols are prefixed with a colon. Symbols are almost the same as a string. However you don't use symbols to write messages, but to give unique names to options or choices.

I wont show you how to add colors to the program as that is a useful exercise.

Keep Track of Time

If you want to practice yourself on improving your speed at doing arithmetic it could be useful to record the time you spend in total on all questions. For that we can use the time() function. It gives the system time in seconds. So by calling it twice and looking at the difference we can find out how many seconds have elapsed.

Modify your program to put on the first line:

t = time()

Then at the end of the loop you put:

dt = round(time() - t)

time() - t finds the seconds elapsed, and round() rounds it off to the nearest whole seconds. Then you can display time like this:

println("Time: $dt")

For Advanced Coders

Once you know more Julia, there are plenty of improvements you can easily make. The version I use at home is contained within a separate function practice() which allow you to configure whether you practice addition, multiplication, subtraction or division. It even lets you practice using different number systems, such as hexadecimal, binary or dozenal (12-base).

function practice(n = 10, range = 1:9, disp = dec, parser = parse; operator = *)
correct = 0
t = time()
for i in 1:n
a = rand(range)
b = rand(range)
msg = join([disp(a), string(operator), disp(b), " = "])
print(msg)
c = parser(readline(STDIN))
if c != operator(a, b)
print(msg, disp(operator(a, b)))
print_with_color(:red, " Wrong\n")

else
print_with_color(:green, "Correct!\n")
correct += 1
end
println("")
end
dt = round(time() - t)
println("$correct/$n")
println("Time: $dt")
end

For instance with my youngest son, I practice addition rather than multiplication. To practice that with the numbers from 2 to 8, 10 times I write:

julia> practice(10, 2:8, operator=+)