Small Basic-Subroutines
Small Basic-Subroutines
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
You execute a subroutine by calling SubroutineName(). As usual, the punctuators “()” are
necessary to tell the computer that you want to execute a subroutine.
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 solve 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 sum,difference,
multiplication and division of the two.
Practice Program::
sum()
diff()
multi
div()
Sub sum
sum=num1+num2
Textwindow.writeline(“The sum of two numbers = ” +sum)
End Sub
Sub diff
diff=num1-num2
Textwindow.writeline(“The difference of two numbers = ” +diff)
End Sub
Sub multi
multi=num1*num2
Textwindow.writeline(“The multiplication of two numbers = ” +multi)
End Sub
Sub div
div=num1/num2
Textwindow.writeline(“The sum of two numbers = ” +div)
End Sub
Practice Program::
Write a program in small basic using subroutine find the square and cube of a number
entered by the user.
Sub square
sq=num1*num1
Textwindow.writeline(“The Square of a numbers = ” +sq)
End Sub
Sub cube
cu=num1*num1*num1
Textwindow.writeline(“The Cube of a number = ” +sq)
End Sub