Contents

We have seen in our chapters on loops that there are many times that we want to repeat certain blocks of code multiple times. A loop repeats these blocks one after the other, but what if we want to repeat a block of code at different times?

We can use a special tool called a subroutine to make a block of code repeatable. We can "call" our subroutine at any point in our program, and when the subroutine ends, the control flow will jump back to where it was.

When we move control flow into a subroutine, we say that we "call" the subroutine, or that we "enter" it. Similarly, when the subroutine has completed, we say that we "exit" the subroutine, or that we "return from it".

One of the big benefits to using subroutines is that they help to make your code much easier to read for other people. Many times the person who writes a program will understand it very well, but it may not be so obvious to other people, such as teammates. For instance, if we have a robot using the BasicStamp, and we want to make that robot walk around in the shape of a square, we can use subroutines to do it easily: