Small Basic > Getting Started Guide > Chapter 9: Subroutines
 
 

Subroutines

Very often while writing programs we’ll run into cases where we’ll have to execute the same set of steps, over and over again. In those cases, it probably wouldn’t make sense to rewrite the same statements multiple times. That’s when Subroutines come in handy.

A subroutine is a portion of code within a larger program that usually does something very specific, and that can be called from anywhere in the program. Subroutines are identified by a name that follows the Sub keyword and is terminated by the EndSub keyword. For example, the following snippet represents a subroutine whose name is PrintTime, and it does the job of printing the current time to the TextWindow.

Sub PrintTime
  TextWindow.WriteLine(Clock.Time)
EndSub

 

Below is a program that includes the subroutine and calls it from various places.

PrintTime()
TextWindow.Write("Enter your name: ")
name = TextWindow.Read()
TextWindow.Write(name + ", the time now is: ")
PrintTime()

Sub PrintTime
  TextWindow.WriteLine(Clock.Time)
EndSub

 

Figure 9.1 - Calling a simple Subroutine
Figure 9.1 - Calling a simple Subroutine

You execute a subroutine by calling SubroutineName(). As usual, the punctuators “()” are necessary to tell the computer that you want to execute a subroutine.

Advantages of using Subroutines

As we just saw above, subroutines help reduce the amount of code you have to type in. Once you have the PrintTime subroutine written, you can call it from anywhere in your program and it’ll print the current time.

Note: Remember, you can only call a SmallBasic subroutine from within the same program. You cannot call a subroutine from within another program.

In addition, subroutines can help decompose complex problems into simpler pieces. Say you had a complex equation to solve, you can write several subroutines that solved smaller pieces of the complex equation. Then you can put the results together to get the solution to the original complex equation.

Subroutines can also aid in improving the readability of a program. In other words, if you have well-named subroutines for commonly run portions of your program, your program becomes easy to read and comprehend. This is very important if you want to understand someone else’s program or if you want your program to be understood by others. Sometimes, it is helpful even when you want to read your own program, say a week after you wrote it.

Using variables

You can access and use any variable that you have in a program from within a subroutine. As an example, the following program accepts two numbers and prints out the larger of the two. Notice that the variable max is used both inside and outside of the subroutine.

TextWindow.Write("Enter first number: ")
num1 = TextWindow.ReadNumber()
TextWindow.Write("Enter second number: ")
num2 = TextWindow.ReadNumber()

FindMax()
TextWindow.WriteLine("Maximum number is: " + max)

Sub FindMax
  If (num1 > num2) Then
    max = num1
  Else
    max = num2
  EndIf
EndSub

 

And the output of this program looks like this.

Figure 9.2 - Max of two numbers using Subroutine
Figure 9.2 - Max of two numbers using Subroutine

Let’s look at another example that will illustrate the usage of Subroutines. This time we’ll use a graphics program that computes various points which it will store in variables x and y. Then it calls a subroutine DrawCircleUsingCenter which is responsible for drawing a circle using x and y as the center

GraphicsWindow.BackgroundColor = "Black"
GraphicsWindow.PenColor = "LightBlue"
GraphicsWindow.Width = 480
For i = 0 To 6.4 Step 0.17
  x = Math.Sin(i) * 100 + 200
  y = Math.Cos(i) * 100 + 200
  
  DrawCircleUsingCenter()
EndFor

Sub DrawCircleUsingCenter
  startX = x - 40
  startY = y - 40
  
  GraphicsWindow.DrawEllipse(startX, startY, 120, 120)
EndSub

 

Figure 9.3 - Graphics Example for Subroutines
Figure 9.3 - Graphics Example for Subroutines

Calling Subroutines inside Loops

Sometimes subroutines get called from inside a loop, during which time they execute the same set of statements but with different values in one or more of the variables. For instance, say if you have a subroutine named PrimeCheck and this subroutine determines if a number is prime or not. You can write a program that lets the user enter a value and you can then say if it is prime or not, using this subroutine. The program below illustrates that.

TextWindow.Write("Enter a number: ")
i = TextWindow.ReadNumber()
isPrime = "True"
PrimeCheck()
If (isPrime = "True") Then
  TextWindow.WriteLine(i + " is a prime number")
Else
  TextWindow.WriteLine(i + " is not a prime number")
EndIf 

Sub PrimeCheck
  For j = 2 To Math.SquareRoot(i)
    If (Math.Remainder(i, j) = 0) Then
      isPrime = "False"
      Goto EndLoop
    EndIf
  Endfor
EndLoop:
EndSub

 

The PrimeCheck subroutine takes the value of i and tries to divide it by smaller numbers. If a number divides i and leaves no remainder, then i is not a prime number. At that point, the subroutine sets the value of isPrime to “False” and exits. If the number was indivisible by smaller numbers then the value of isPrime remains as “True.”

Figure 9.4 - Prime Check
Figure 9.4 - Prime Check

Now that you have a subroutine that can do the Prime test for us, you might want to use this to list out all the prime numbers below, say, 100. It is really easy to modify the above program and make the call to PrimeCheck from inside a loop. This gives the subroutine a different value to compute each time the loop is run. Let’s see how this is done with the example below.

For i = 3 To 100
  isPrime = "True"
  PrimeCheck()
  If (isPrime = "True") Then
    TextWindow.WriteLine(i)
  EndIf
EndFor

Sub PrimeCheck
  For j = 2 To Math.SquareRoot(i)
    If (Math.Remainder(i, j) = 0) Then
      isPrime = "False"
      Goto EndLoop
    EndIf
  Endfor
EndLoop:
EndSub

 

In the program above, the value of i is updated every time the loop is run. Inside the loop, a call to the subroutine PrimeCheck is made. The subroutine PrimeCheck then takes the value of i and computes whether or not i is a prime number. This result is stored in the variable isPrime which is then accessed by the loop outside of the subroutine. The value of i is then printed if it turns out to be a prime number. And since the loop starts from 3 and goes up to 100, we get a list of all the prime numbers that are between 3 and 100. Below is the result of the program.

Figure 9.5 - Prime Numbers
Figure 9.5 - Prime Numbers

Next Chapter