Small Basic >Small Basic Books >The Developer’s Reference Guide to Small Basic > 2. Overview of Small Basic 


In this chapter, we are concerned with writing code for our programs. We will provide an overview of many of the elements of the language used in Small Basic. This chapter is essentially a self-contained guide to the Small Basic language. This will give us the foundation needed to begin learning about Small Basic objects and writing more detailed programs.

A Brief History of BASIC

The BASIC language was developed in the early 1960's at Dartmouth College as a device for teaching programming to “ordinary” people. There is a reason it’s called BASIC:

B (Beginner's)
A (All-Purpose)
S (Symbolic)
I (Instruction)
C (Code)

When timesharing systems were introduced in the 1960’s, BASIC was the language of choice. Many of the first computer simulation games (Star Trek, for example) were written in timeshare BASIC. In the mid-1970's, two college students decided that the new Altair microcomputer needed a BASIC language interpreter. They sold their product on cassette tape for a cost of $350. You may have heard of these entrepreneurs: Bill Gates and Paul Allen!

The Developer’s Reference Guide

This chapter is adapted from the book The Developer’s Reference Guide To Microsoft Small Basic by Philip Conrod and Lou Tylee.

To purchase this book in its entirety, please see the Computer Science For Kids web site.

Every BASIC written since then has been based on that early version. Examples include: GW-Basic, QBasic, QuickBasic, Visual Basic. All the toy computers of the early 80’s (anyone remember TI99/4A, Commodore 64, Timex, Atari 400?) used BASIC for programming. Small Basic continues the tradition of BASIC programming. It uses the simple concepts of the early BASIC language with a modern development environment.

This chapter provides an overview of the BASIC language used in the Small Basic environment. If you’ve ever used another programming language (or some version of BASIC), you will see equivalent structures in the language of Small Basic.


Variables are used by Small Basic to hold information needed by an application. Variables must be properly named. Rules used in naming variables:

  • No more than 40 characters
  • They may include letters, numbers, and underscore (_)
  • The first character must be a letter
  • You cannot use a reserved word (keywords used by Small Basic)

Use meaningful variable names that help you (or other programmers) understand the purpose of the information stored by the variable.

Examples of acceptable variable names:

StartingTime Interest_Value Letter05
JohnsAge Number_of_Days TimeOfDay

Small Basic Data Types

Each variable is used to store information of a particular type. Small Basic uses three types of data: numeric, string (or text) and Boolean variables. You must always know the type of information stored in a particular variable.

Numeric variables can store integer or decimal numbers. They can be positive or negative.

A string variable is just that – one that stores a string (list) of various characters. A string can be a name, a string of numbers, a sentence, a paragraph, any characters at all. And, many times, a string will contain no characters at all (an empty string). We will use lots of strings in Small Basic, so it’s something you should become familiar with. Strings are always enclosed in quotes (““). Examples of strings:

“I am a Small Basic programmer” “012345” “Title Author”

Boolean variables can have one of two different string values: “true” or “false”. The quotes are need to indicate these are string values. Boolean variables are helpful in making decisions.

With all the different variable types, we need to be careful not to improperly mix types. We can only do mathematical operations on numbers (integer and decimal types). String types must only work with other string types. Boolean types are used for decisions.

Small Basic has no requirements (or capabilities) for declaring variables before they are used. They are essentially declared the first time they are used.


Small Basic has facilities for handling arrays, which provide a way to store a large number of variables under the same name. Each variable, called an element, in an array must have the same data type, and they are distinguished from each other by an array index which is enclosed in brackets [].

Arrays are used in a manner identical to that of regular variables. For example, the ninth element of an array named Item is:


The index on an array variable begins at 0 and ends at the highest value used. Hence, the Item array in the above example actually has ten elements, ranging from Item[0] to Item[9]. This is different than other languages. You use array variables just like any other variable - just remember to include its name and its index. Many times, the 0 index is ignored and we just start with item 1. But sometimes the 0th element cannot be ignored. You will see examples of both 0-based and 1-based arrays in the course examples.

You can have multi-dimensional arrays. A two-dimensional array element is written as:


This refers to the element in the 2nd row and 7th column of the array AnotherArray.

Intellisense Feature

Working within the code editor window is easy. You will see that typing code is just like using any word processor. The usual navigation and editing features are all there.

One feature that you will become comfortable with and amazed with is called Intellisense. As you type code, the Intellisense feature will, at times, provide assistance in completing lines of code. For example, once you type an object name and a dot (.), a drop-down list of possible properties and methods will appear.

Intellisense is a very useful part of Small Basic. You should become acquainted with its use and how to select suggested values. We tell you about now so you won’t be surprised when little boxes start popping up as you type code.

Small Basic Statements and Expressions

The simplest (and most common) statement in Small Basic is the assignment statement. It consists of a variable name, followed by the assignment operator (=), followed by some sort of expression. The expression on the right hand side is evaluated, then the variable (or property) on the left hand side of the assignment operator is replaced by that value of the expression.


StartTime = Now ExplorerName = "Captain Spaulding" TextWindow.Title = "My Program" BitCount = ByteCount * 8 Energy = Mass * LightSpeed * LightSpeed NetWorth = Assets - Liabilities

The assignment statement stores information.

Comment statements begin with a single quote ('). For example:

' This is a comment x = 2 * y ' another way to write a comment

You, as a programmer, should decide how much to comment your code. Consider such factors as reuse, your audience, and the legacy of your code. In our notes and examples, we try to insert comment statements when necessary to explain some detail.

Small Basic Arithmetic Operators

Operators modify values of variables. The simplest operators carry out arithmetic operations. There are four arithmetic operators in Small Basic.

Addition is done using the plus (+) sign and subtraction is done using the minus (-) sign. Simple examples are:

Operation Example Result
Addition 7 + 2 9
Addition 3.4 + 8.1 11.5
Subtraction 6 - 4 2
Subtraction 11.1 – 7.6 3.5

Multiplication is done using the asterisk (*) and division is done using the slash (/). Simple examples are:

Operation Example Result
Multiplication 8 * 4 32
Multiplication 2.3 * 12.2 28.06
Division 12 / 2 6
Division 45.26 / 6.2 7.3

The mathematical operators have the following precedence indicating the order they are evaluated without specific groupings:

  1. Multiplication (*) and division (/)
  2. Addition (+) and subtraction (-)

If multiplications and divisions or additions and subtractions are in the same expression, they are performed in left-to-right order. Parentheses around expressions are used to force some desired precedence.

Comparison and Logical Operators

There are six comparison operators in Small Basic used to compare the value of two expressions (the expressions must be of the same data type). These are the basis for making decisions:

Operator Comparison
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
= Equal to
<> Not equal to

It should be obvious that the result of a comparison operation is a Boolean value (“true” or “false”). Examples:

A = 9.6, B = 8.1, A >B returns “true”
A = 14, B = 14, A < B returns “false”
A = 14, B = 14, A >= B returns “true”
A = 7, B = 11, A <= B returns “true”
A = “Small”, B=”Small”, A = B returns “true”
A = “Basic”, B = “Basic”, A <> B returns “false”

Logical operators operate on Boolean data types, providing a Boolean result. They are also used in decision making. We will use two logical operators

Operator Operation
And Logical And
Or Logical Or

The And operator checks to see if two different Boolean data types are both “true”. If both are “true”, the operator returns a “true”. Otherwise, it returns a “false” value. Examples:

A = “true”, B = “true”, then A And B = “true”
A = “true”, B = “false”, then A And B = “false”
A = “false”, B = “true”, then A And B = “false”
A = “false”, B = “false”, then A And B = “false”

The Or operator checks to see if either of two Boolean data types is “true”. If either is “true”, the operator returns a “true”. Otherwise, it returns a “false” value. Examples:

A = “true”, B = “true”, then A Or B = “true”
A = “true”, B = “false”, then A Or B = “true”
A = “false”, B = “true”, then A Or B = “true”
A = “false”, B = “false”, then A Or B = “false”

Logical operators follow arithmetic operators in precedence. Use of these operators will become obvious as we delve further into coding.

Concatenation Operator

To concatentate two string data types (tie them together), use the + symbol, the string concatenation operators:

CurrentTime = "The current time is " + TimeNow SampleText = "Hook this " + "to this"

Math Functions

Small Basic provides a set of methods (or functions) that perform tasks such as square roots, trigonometric relationships, and exponential functions. Yes, some programming does involve math!

Each of the Small Basic math functions comes from the Math class. All this means is that each function name must be preceded by Math. (say Math-dot) to work properly. The functions and the returned values are listed below.

Math Functions:

Math.Abs(x) Returns the absolute value of x. Math.ArcSin(x) Returns the angle in radians, given the sine value x. Math.ArcTan(x) Returns the angle in radians, given the tangent value x. Math.Ceiling(x) Gets an integer that is greater than or equal to x. For example, 32.233 will return 33. Math.Cos(x) Returns a value containing the cosine of the specified angle (x) in radians. Math.Floor(x) Gets an integer that is less than or equal to x. For example, 32.233 will return 32. Math.GetDegrees(x) Converts a given angle (x) in radians to degrees. Math.GetRadians(x) Converts a given angle (x) in degrees to radians. Math.GetRandomNumber(x) Gets a random number between 1 and x (inclusive). Math.Log(x) Gets the logarithm (base 10) value of the given number x. Math.Max(x,y) Returns the larger of two numbers x and y. Math.Min(x,y) Returns the smaller of two numbers x and y. Math.NaturalLog(x) Gets the natural logarithm value of the given number x. Math.Pi() A constant that specifies the ratio of the circumference of a circle to its diameter (3.14159265359…). Math.Power(x,y) Raises a number (x) to a specified power (y(. Math.Remainder(x,y) Divides the first number (x) by the second (y) and returns the remainder. Math.Round(x,y) Rounds x to the nearest integer. For example 32.233 will be rounded to 32.0 while 32.566 will be rounded to 33. Math.Sin(x) Returns a value containing the sine of the specified angle (x) in radians. Math.SquareRoot(x) Returns a value specifying the square root of a number x. Math.Tan(x) Returns a value containing the tangent of an angle (x)in radians.


Math.Abs(-5.4) returns the absolute value of –5.4 (returns 5.4) Math.Cos(2.3) returns the cosine of an angle of 2.3 radians Math.Max(7, 10) returns the larger of the two numbers (returns 10) Math.Power(2, 4) returns 2 raised to the fourth power (16) Math.SquareRoot(4.5) returns the square root of 4.5

Random Numbers

We single out one math method for its importance. In writing games and learning software, we use a random number generator to introduce unpredictability. The Math.GetRandomNumber method is used in Small Basic for random numbers.

Whenever you need a random whole number (integer) value, use this method:


This statement generates a random integer value that is between 1 and Limit. For example, the method:


will generate random numbers from 1 to 5. The possible values will be 1, 2, 3, 4 and 5.

A roll of a die can produce a number from 1 to 6. To use GetRandomNumber to roll a die, we would write:

DieNumber = Math.GetRandomNumber(6)

For a deck of cards, the random integers would range from 1 to 52 since there are 52 cards in a standard playing deck. Code to do this:

CardNumber = Math.GetRandomNumber(52)

If we want a number between -100 and 100, we would use:

YourNumber = 101 - Math.GetRandomNumber(201)

Check the examples above to make sure you see how the random number generator produces the desired range of integers.

Small Basic Decisions - If Statements

The concept of an If statement for making a decision is very simple. We check to see if a particular condition is “true”. If so, we take a certain action. If not, we do something else. If statements are also called branching statements. Branching statements are used to cause certain actions within a program if a certain condition is met.

The simplest branching statement is:

If (Condition) Then [process this code] EndIf

Here, if Condition is true”, the code bounded by the If/EndIf is executed. If Condition is “false”, nothing happens and code execution continues after the EndIf statement.


If (Balance - Check < 0) Then Trouble = "true" CheckingStatus = "Red" EndIf

In this case, if Balance - Check is less than zero, two lines of information are processed: Trouble is set to “true” and the CheckingStatus has a value of “Red”. Notice the indentation of the code between the If and EndIf lines. The Small Basic Intellisense feature will automatically do this indentation. It makes understanding (and debugging) your code much easier.

What if you want to do one thing if a condition is “true” and another if it is “false”? Use an If/Then/Else/EndIf block:

If (Condition) Then [process this code] Else [process this code] EndIf

In this block, if Condition is “true”, the code between the If and Else lines is executed. If Condition is “false”, the code between the Else and EndIf statements is processed.


If (Balance - Check < 0) Then Trouble = "true" CheckingStatus = "Red" Else Trouble = "false" CheckingStatus = "Black" EndIf

Here, the same two lines are executed if you are overdrawn (Balance - Check < 0), but if you are not overdrawn (Else), the Trouble flag is turned off and your CheckingStatus is “Black”.

Finally, we can test multiple conditions by adding the ElseIf statement:

If (Condition1) Then [process this code] ElseIf (Condition2) Then [process this code] ElseIf (Condition3) Then [process this code] Else [process this code] EndIf

In this block, if Condition1 is “true”, the code between the If and first ElseIf line is executed. If Condition1 is “false”, Condition2 is checked. If Condition2 is “true”, the indicated code is executed. If Condition2 is not true, Condition3 is checked. Each subsequent condition in the structure is checked until a “true” condition is found, a Else statement is reached or the EndIf is reached.


If (Balance - Check < 0) Then Trouble = "true" CheckingStatus = "Red" ElseIf (Balance – Check = 0) Then Trouble = "false" CheckingStatus = "Yellow" Else Trouble = "false" CheckingStatus = "Black" EndIf

Now, one more condition is added. If your Balance equals the Check amount (ElseIfBalance - Check = 0), you’re still not in trouble and the CheckingStatus is “Yellow”.

In using branching statements, make sure you consider all viable possibilities in the If/Else/EndIf structure. Also, be aware that each If and ElseIf in a block is tested sequentially. The first time an If test is met, the code associated with that condition is executed and the If block is exited. If a later condition is also “true”, it will never be considered.

Small Basic Looping

Many applications require repetition of certain code segments. For example, you may want to roll a die (simulated die of course) until it shows a six. Or, you might generate financial results until a certain sum of returns has been achieved. This idea of repeating code is called iteration or looping.

In Small Basic, one way of looping is with the While loop:

While (Condition) ' Small Basic code block to repeat while Condition is true EndWhile

In this structure, all code between While and EndWhile is repeated while the given logical Condition is “true.

Note a While loop structure will not execute even once if Condition is “false” the first time through. If we do enter the loop (Condition is “true”), it is assumed at some point Condition will become false to allow exiting. Once this happens, code execution continues at the statement following the EndWhile statement. This brings up a very important point about loops – if you get in one, make sure you get out at some point. In the While loop, if Condition is always “true”, you will loop forever – something called an infinite loop.


Counter = 1 While (Counter <= 1000) Counter = Counter + 1 EndWhile

This loop repeats as long as (While) the variable Counter is less than or equal to 1000.

Another Example:

Rolls = 0 Counter = 0 While (Counter < 10) ' Roll a simulated die Rolls = Rolls + 1 If (Math.GetRandomNumber(6) = 6) Then Counter = Counter + 1 EndIf EndWhile

This loop repeats while the Counter variable remains less than 10. The Counter variable is incremented (increased by one) each time a simulated die rolls a 6 (the GetRandomNumber function used here returns a random value from 1 to 6). The Rolls variable tells you how many rolls of the die were needed to roll 10 sixes. Theoretically, it should take 60 rolls since there is a 1 in 6 chance of rolling a six.

As mentioned, if the logical condition used by a While loop is “false” the first time the loop is encountered, the code block in the While loop will not be executed. This may be acceptable behavior – it may not be.

We can build a loop that will always be executed at least once. To do this we need to introduce the Small Basic Goto statement. A Goto allows you to transfer code execution to anywhere in your code. A Goto requires a label. A label is like a bookmark – it can be named anything you want. A label name is always followed by a colon. An example is:


Anytime we want to transfer program execution to this label statement, we use a Goto:

Goto MyLabel

You do not write the colon in the Goto statement.

Using these new concepts in a loop, we have what we’ll call a Goto loop:

MyLabel: ' Small Basic code block to process If (Condition) Then Goto MyLabel EndIf

The code block repeats as long as Condition is “true”. Unlike the While loop, this loop is always executed at least once. Somewhere in the loop, Condition should be changed to “false” to allow exiting.

Let’s look at examples of the Goto loop. What if we want to keep adding three to a Sum until the value exceeds 50. This loop will do it:

Sum = 0 SumLoop: Sum = Sum + 3 If (Sum <= 50) Then Goto SumLoop EndIf

Another Dice Example:

Sum = 0 Rolls = 0 SumLoop: ' Roll a simulated die Die = Math.GetRandomNumber(6) Sum = Sum + Die Rolls = Rolls + 1 If (Sum <= 30) Then Goto SumLoop EndIf

This loop rolls a simulated die (Die) while the Sum of the rolls does not exceed 30. It also keeps track of the number of rolls (Rolls) needed to achieve this sum.

You need to decide which of the loop structures (While, Goto) fits your program. Recall the major difference is that a Goto loop is always executed at least once; a While loop may never be executed.

And, make sure you can always get out of a loop. In both looping structures, this means that, at some point, the checking logical condition must become “false” to allow exiting the loop. When you exit a While loop, processing continues at the next Small Basic statement after the EndWhile. In a Goto loop, processing continues at the Small Basic statement after the If structure checking whether the loop should repeat.

If, at some point in the code block of a loop, you decide you need to immediately leave the loop or move to another point in the code, a Goto statement can also do this. You just need a label statement at the appropriate place. When the Goto statement is encountered, processing is immediately transferred to the labeled statement.

Small Basic Counting

With While loop structures, we usually didn’t know, ahead of time, how many times we execute a loop or iterate. If you know how many times you need to iterate on some code, you want to use Small Basic counting. Counting is useful for adding items to a list or perhaps summing a known number of values to find an average.

Small Basic counting is accomplished using the For loop:

For Variable = Start To End Step Increment ' Small Basic code to execute goes here EndFor

In this loop, Variable is the counter (doesn’t necessarily need to be a whole number). The first time through the loop, Variable is initialized at Start. Each time the corresponding EndFor statement is reached, Variable is incremented by an amount Increment. If the Step value is omitted, a default increment value of one is used. Negative increments are also possible. The counting repeats until Variable equals or exceeds the final value End.


For Degrees = 0 To 360 Step 10 'convert to radians R = Degrees * Math.PI / 180 A = Math.Sin(R) B = Math.Cos(R) C = Math.Tan(R) EndFor

In this example, we compute trigonometric functions for angles from 0 to 360 degrees in increments (steps) of 10 degrees.

Another Example:

For Countdown = 10 To 0 Step -1 TextWindow.WriteLine(Countdown + " Seconds") EndFor

NASA called and asked us to countdown from 10 to 0. The loop above accomplishes the task.

And, Another Example:

Sum = 0 For I = 1 to 100 Sum = Sum + MyValues[I] EndFor Average = Sum / 100

This code finds the average value of 100 numbers stored in the array MyValues. It first sums each of the values in a For loop. That sum is then divided by the number of terms (100) to yield the average.

You may exit a For loop early using an Goto statement. This will transfer program control to the corresponding labeled statement, usually the line after the EndFor.

Small Basic Subroutines

In the looping discussion, we saw how code in one particular block could be repeated until some desired condition was met. Many times in Small Basic programs, we might have a need to repeat a certain block of code at several different points in the program. Why would you want to do this?

Say we had a game that requires us to roll 5 dice and add up their individual values to yield a sum. What if we needed to do this at 10 different places in our program? We could write the code, then copy and paste it to the 10 different places. I think you can see problems already. What if you need to change the code? You would need to change it in 10 different places. What if you needed to put the code in another place in your program? You would need to do another ‘copy and paste’ operation. There’s a better way. And that way is to use a Small Basic subroutine.

A subroutine allows you to write the code to perform certain tasks just once. Then, whenever you need to access the code in your program, you can “call it,” providing any information it might need to do its tasks. Subroutines are the building blocks of a Small Basic program. Using subroutines in your Small Basic programs can help divide a complex application into more manageable units of code. Just think of a subroutine as a code block you can access from anywhere in a Small Basic program. When you call the subroutine, program control goes to that subroutine, performs the assigned tasks and returns to the calling program. It’s that easy.

Let’s see how to create and call a subroutine. Subroutines go at the end of your ‘main’ program code. A subroutine named MySubroutine would have the form (starts with a Sub keyword and ends with EndSub):

Sub MySubroutine ' Code to be executed in the subroutine EndSub

You execute, or call, this subroutine using:


The parentheses are needed to tell the computer you are executing a subroutine. When the subroutine is called, the corresponding code is executed until the EndSub line is reached. At this point, program execution returns to the line of code immediately after the line that called the subroutine.

A subroutine can access and use any variable you use in your program. Likewise, your program can use any variables defined in your subroutines. In computer talk, we say all variables in a Small Basic program have global scope.

Let’s try to make this clearer by looking at a subroutine example. We’ll do the dice example of rolling five dice and computing their sum. The subroutine that accomplishes this task is:

Sub RollDice Die1 = Math.GetRandomNumber(6) Die2 = Math.GetRandomNumber(6) Die3 = Math.GetRandomNumber(6) Die4 = Math.GetRandomNumber(6) Die5 = Math.GetRandomNumber(6) SumDice = Die1 + Die2 + Die3 + Die4 + Die5 EndSub

This subroutine is named RollDice and the variable SumDice has the resulting sum.

Using this subroutine, any time you need the sum of five dice in your program, you would use:

RollDice() A = SumDice

After this code is executed, the variable A will have sum of five dice.

As you progress in your Small Basic programming education, you will become more comfortable with using subroutines and see how useful they are. In the remainder of this course, we will use subroutines for much of the code. Study each example to help learn how to build and use subroutines.

Small Basic Objects

Objects are used by the Small Basic language to help build programs. An object can have properties, methods and/or events.

A property describes something about the object. In Chapter 1, we had this simple line of code:

TextWindow.Title = "Hello Program"

Here TextWindow is the object, Title is the property (the information that appears in the window title bar) and “Hello Program” is the value of the property. So, in general, to set the Property of an Object, you use this “dot-notation”:

Object.Property = Value

A method does something to an object. Again, in Chapter 1, we had this line:

TextWindow.WriteLine("This is the first line of the program.")

Here, WriteLine is the method (it writes information in the text window) and the item in the parentheses is called the method argument. The argument (or sometimes arguments) provides information needed by the method to do its job. To apply a Method to an Object, use:


Sometimes, the method may compute and return a value. In this case, that Value is found using:

Value = Object.Method(Arguments)

Lastly, an event is something that happens to an object. Example events are clicking a button control, pressing a mouse button or pressing a key on the keyboard. To respond to an event, the event must be assigned a subroutine that is called if the event occurs. To assign the subroutine EventSub to the Event for Object, use:

Object.Event = EventSub

In the next several chapters, we look at objects and how to use them. For each object, we review the properties, methods and events (if any).

Chapter Review

After completing this chapter, you should understand:

  • How to properly use variables.
  • Small Basic statements.
  • The assignment operator, mathematics operators, comparison and logic operators and concatenation operators.
  • The wide variety of built-in Small Basic methods, especially string methods and mathematics methods.
  • How to use graphics methods to draw in the graphics window.
  • The If/Then/ElseIf/Else/EndIf structure used for branching and decisions.
  • How the While loop and Goto loop work.
  • How the For loop is used for counting.
  • The importance of subroutines in Small Basic programs.
  • Properties, methods and events, as related to Small Basic objects.

We now have the foundation needed to start writing some programs. To do this, we will cover many of the Small Basic objects, starting with the Program object.

Next Chapter > >

Excerpt © Copyright 2010-2013 By Kidware Software LLC All Rights Reserved. Computer Science For Kids, the Computer Science For Kids logo, and related trade dress are trademarks or registered trademarks of Kidware Software LLC. Philip Conrod & Lou Tylee have co-authored dozens of books and tutorials for beginning Microsoft Basic, Small Basic, Visual Basic, and Visual C# developers of all ages for over 25 years.