LessonsBeginner: First stepsLesson 11

Counting loops

Do something a number of times, count up or down, and add things up as you go.

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

Again and again

A loop runs the same lines more than once. The simplest says how many times:

ExampleRun it in the playground
repeat 3 times
   put "Hip hip hooray!"
end repeat
Output
Hip hip hooray!
Hip hip hooray!
Hip hip hooray!

Counting with a variable

repeat with counts in a variable for you: it starts at the first number, runs the lines, adds one, and stops after the last number. Short names like i are traditional for a counter.

ExampleRun it in the playground
repeat with i = 1 to 5
   put i && "squared is" && i * i
end repeat
Output
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25

Counting down, and in steps

down to counts backwards. step says how much to add each time, and can be negative.

ExampleRun it in the playground
repeat with tCount = 3 down to 1
   put tCount & "..."
end repeat
put "Lift off!"
repeat with i = 0 to 20 step 5
   put i
end repeat
Output
3...
2...
1...
Lift off!
0
5
10
15
20

Adding things up

A loop and a variable that grows are a pair you will use all the time. Here is the sum of 1 to 100, which the young Carl Friedrich Gauss is said to have worked out in his head:

ExampleRun it in the playground
put 0 into tTotal
repeat with i = 1 to 100
   add i to tTotal
end repeat
put tTotal
Output
5050

And a string can grow the same way, with put ... after:

ExampleRun it in the playground
repeat with i = 1 to 5
   put i * 7 & space after tTable
end repeat
put "Sevens:" && tTable
put "Stars:" && tStars
repeat 4 times
   put "*" after tStars
end repeat
put "Stars:" && tStars
Output
Sevens: 7 14 21 28 35 
Stars: tStars
Stars: ****

Look at the second line of Output: before anything was put into tStars, xTalk read the name as a word (an unquoted literal, from the lesson on variables). Once the loop filled it, it is a variable.

A loop in a loop

Loops can go inside each other. The inner loop runs all the way through for every turn of the outer one: here, a little multiplication table.

ExampleRun it in the playground
repeat with tRow = 1 to 3
   put empty into tLine
   repeat with tColumn = 1 to 4
      put tRow * tColumn & tab after tLine
   end repeat
   put tLine
end repeat
Output
1	2	3	4	
2	4	6	8	
3	6	9	12	

Try it yourself

The factorial of a number is all the whole numbers up to it multiplied together: 4 factorial is 1 × 2 × 3 × 4 = 24. Use a loop to put the factorial of 10.

Show a solution
ExampleRun it in the playground
put 1 into tResult
repeat with i = 1 to 10
   multiply tResult by i
end repeat
put tResult
Output
3628800

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.