LessonsBeginner: First stepsLesson 5

Arithmetic

Sums with + - * / and ^, whole-number division with div and mod, and the commands that change a number in place.

  • Beginner
  • Lesson 5 of 83
  • About 8 minutes
  • 7 examples

The operators

xTalk uses the symbols you know from maths, with * for times, / for divide and ^ for "to the power of".

ExampleRun it in the playground
put 7 + 5
put 7 - 5
put 7 * 5
put 7 / 5
put 2 ^ 10
Output
12
2
35
1.4
1024

Whole numbers: div and mod

div divides and drops the part left over. mod gives only what is left over. They are more useful than they look: mod 2 tells you whether a number is even, and the pair turns seconds into minutes and seconds.

ExampleRun it in the playground
put 17 div 5
put 17 mod 5
put 10 mod 2 -- 0: 10 is even
put 125 div 60 & ":" & 125 mod 60
put 200 div 60 && "hours" && 200 mod 60 && "minutes"
Output
3
2
0
2:5
3 hours 20 minutes

Which goes first

As in maths, ^ comes first, then *, /, div and mod, then + and -. Operators of the same kind go from left to right. Brackets change the order, and make a long sum easier to read even when they do not.

ExampleRun it in the playground
put 2 + 3 * 4
put (2 + 3) * 4
put 10 - 4 - 3
put 2 * 3 ^ 2
put (2 * 3) ^ 2
Output
14
20
3
18
36

Decimals

Division gives decimals when it needs them. xTalk keeps many digits, but shows at most six decimal places unless you ask for more.

ExampleRun it in the playground
put 10 / 4
put 10 / 3
put 0.1 + 0.2
put 0.1 + 0.2 = 0.3
Output
2.5
3.333333
0.3
true

Changing a number in place

Four commands change the number in a variable directly. They read like the sentences you would say:

ExampleRun it in the playground
put 100 into tMoney
add 20 to tMoney
subtract 5 from tMoney
multiply tMoney by 2
divide tMoney by 10
put tMoney
Output
23

add 1 to tCount is the xTalk way of counting: you will see it in nearly every program with a loop. A variable that has nothing in it counts as 0, so you do not even need to start it at 0 first.

Dividing by zero

A number divided by zero has no answer, so xTalk stops with an error rather than make one up.

A mistakeIt stops with an error on line 2
put 0 into tPlayers
put 100 / tPlayers

When a value might be zero, check it first with if (the subject of Making decisions).

Try it yourself

A film lasts 137 minutes. Put its length in hours and minutes, like 2 hours 17 minutes. Then work out how many seconds there are in a week.

Show a solution
ExampleRun it in the playground
put 137 into tMinutes
put tMinutes div 60 && "hours" && tMinutes mod 60 && "minutes"
put 7 * 24 * 60 * 60
Output
2 hours 17 minutes
604800

Words in this lesson

Each one finds every lesson that uses it. The Dictionary has the whole story of each, with its syntax and more examples.