Beginning Microsoft Small Basic: Chapter 3: Your First Small Basic Program
Small Basic > Small Basic Books > Beginning Microsoft Small Basic** **> 3. Your First Small Basic Program
Review and PreviewIn the first two classes, you’ve learned about the structure of a Small Basic program, some rules for typing code, and how to run a Small Basic program. Do you have some ideas of programs you would like to build using Small Basic? If so, great. Beginning with this class, you will start to develop your own programming skills. In each class to come, you will learn some new features of the Small Basic language. In this class, you will write your first Small Basic program. To do this, you first need to learn about some of the basic components of the Small Basic language. You will learn about variables, assignment statements and some simple operators. Creating a Small Basic ProgramRecall from Class 2 that a Small Basic statement does something. In the Welcome example, we saw a statement that printed some information (“Welcome to Beginning Small Basic!”). Each program we build in this class will be made up of many Small Basic statements for the computer to process. Creating a computer program using Small Basic (or any other language) is a straightforward process. You have a particular task you would like the computer to do for you. You tell the computer in a logical, procedural set of steps how to accomplish that task. |
http://msdn.microsoft.com/hh182234.BeginningSB-med(en-us,MSDN.10).png This chapter is adapted from the book BEGINNING 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. |
It’s relatively easy to write out solution steps to a problem in our language (English, in these notes). The difficult part is you have to talk to the computer in its own language. It would be nice if we could just write “Hey computer, here’s two numbers – add them together and tell me the sum.” A human might understand these instructions, but a computer won’t. Why? First, the computer needs to be told how to do tasks in very specific, logical steps. For this little addition example, the steps would be:
- Give a value to the first number.
- Give a value to the second number.
- Add the first number to the second number, resulting in the sum, a third number.
- Tell me the sum.
Next, we need to talk to the computer in its own language. We translate each solution step into a statement (or statements) in the computer’s language. And, in this course, the computer’s language is Small Basic. To be able to tell the computer how to do any task, you need to have a thorough understanding of the Small Basic language. Your understanding of Small Basic will allow you to translate your programming steps into a language the computer can understand.
Another thing to remember as you write Small Basic programs is that you need to be logical and exact. A computer will follow your instructions – even if they’re wrong! So, as you learn Small Basic, we will emphasize the need to be exact. Once you write exact and logical Small Basic code, the computer is very good and fast at doing its job. And, it can do some pretty amazing things. Let’s look at a couple of other examples of writing out a programming task as a series of steps to illustrate some things a computer can do.
What if the local school principal asks you to average the test scores of the 352 students in the school? Those steps are:
- Determine the score of each student.
- Add up the 352 scores to get a sum.
- Divide the sum by 352 to get the average value.
- Tell the principal the average.
Not too hard, huh? Notice here that the second step can be further broken down into smaller steps. To add up 352 scores, you would:
- Start with the first score.
- Add in the second score, then the third score, then the fourth score, etc.
- Stop when all scores have been added.
In these steps, the computer would do the same task (adding a number) 352 times. Computers are very good at repeating tasks – we will see that this process of repetition is called looping. You will build code for this example in Class 7.
Computers are also very good at playing games with you (that’s why video games are so popular). Have you ever played the card game “War?” You and another player take a card from a standard playing deck. Whoever has the ‘highest’ card wins the other player’s card. You then each get another card and continue the comparison process until you run out of cards. Whoever has the most cards once the game stops is declared the winner. Playing this game would require steps similar to these:
- Shuffle a deck of cards.
- Give a card to the first player.
- Give a card to the second player.
- Determine which card is higher and declare a winner.
- Repeat the process of giving cards to players until you are out of cards.
Things are a bit more complicated here, but the computer is up to the task. The first step requires the computer to shuffle a deck of cards. How do you tell a computer how to do this? Well, before this course is over, you will know how. For now, just know that it’s a series of several programming steps. We will put the Small Basic program for such a specific task in its own area called a subroutine. This makes the program a little easier to follow and also allows use this code in other programs. Notice Step 4 requires the computer to make a decision – determining which card is higher. Computers are very good at making decisions. Finally, Step 5 asks us to repeat the handing out of cards – another example of looping. You will also build this program in Class 7.
If all of these concepts are not clear at the moment, that’s okay. They will become clearer as you progress through this course. I just wanted you to have some idea of what you can do with Small Basic programs. Just remember, for every Small Basic program you create, it is best to first write down a series of logical steps you want the computer to follow in performing the tasks needed by your program. Then, converting those steps into the Small Basic language will give you your Small Basic program – it’s really that simple. This class begins instruction in the elements of Small Basic. And, in subsequent classes, you learn more and more Small Basic, adding to your Small Basic vocabulary. We’ll start slow. By the end of this course, you should be pretty good at “talking Small Basic.”
Small Basic - The First Lesson
At long last, we are ready to get into the heart of a Small Basic program - the Small Basic language. In this class, we will discuss variables (name and type), assignments, arithmetic operations, and techniques for working with a particular type of variable called strings. In each subsequent class in this course, you will learn something new about the Small Basic language.
Variables
All computer programs work with information of one kind or another. Numbers, text, dates and pictures are typical types of information they work with. Computer programs need places to store this information while working with it. What if we need to know how much ten bananas cost if they are 25 cents each? We would need a place to store the number of bananas, the cost of each banana, and the result of multiplying these two numbers together. To store such information, we use something called variables. They are called variables because the information stored there can change, or vary, during program execution. Variables are the primary method for moving information around in a Small Basic program. And, certain rules must be followed in the use of variables.
Variable Names
You must name every variable you use in your program. Rules for naming variables are:
- Can only use letters, numbers, and the underscore (_) character (though the underscore character is rarely used).
- The first character must be a letter. It is customary, though not required, in Small Basic that this first letter be upper case
- You cannot use a word reserved by Small Basic (for example, you can’t have a variable named WriteLine or one named TextWindow).
If a variable name consists of more than one word, the words are joined together, and each word after the first begins with an uppercase letter
The most important rule is to use variable names that are meaningful. You should be able to identify the information stored in a variable by looking at its name. As an example, in our banana buying example, good names would be:
Quantity
Variable Name
Cost of each banana
BananaCost
Number of bananas purchased
NumberBananas
Cost of all bananas
TotalBananaCost
As mentioned in an earlier class, the Small Basic language is not case sensitive. This means the names BananaCost and bananacost refer to the same variable. Try to be consistent in how you write variable names. And make sure you assign unique names to each variable. A nice feature of the Small Basic intellisense feature is that as you add variables to your program, the variable names are added to the list of choices available in the intellisense drop-down menu.
Variable Types
We need to know the type of information stored by each variable. Does it contain a number? Does the number have a decimal point? Does it just contain text information? Let’s look at some variable types.
The first variable type is the integer type. This type of variable is used to represent whole, non-decimal, numbers. Examples of such numbers are:
1 | -20 | 4000 |
Notice you write 4,000 as 4000 in Small Basic – we can’t use commas in large numbers. In our banana example, NumberBananas would an integer type variable.
What if the variable you want to use will have decimal points. In this course, such variables will be of floating type (the decimal point being the thing that “floats”). All you need to know about floating type variables is that they are numbers with decimal points. Examples of such numbers:
-1.25
3.14159
22.7
In our banana example, the variables BananaCost and TotalBananaCost would be floating type variables.
The next variable type is a string variable. 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” |
One last variable type is the boolean variable. It takes its name from a famous mathematician (Boole). It can have one of two values: true or false. Many languages have true and false as reserved words for use with Boolean variables. Small Basic does not have such reserved words. In Small Basic, we will use string values of “true” and “false” to provide a representation for boolean variables. We will see that such variables are at the heart of the computer’s decision making capability. If wanted to know if a banana was rotten, we could name a boolean variable IsBananaRotten. If this was “true”, the banana is indeed rotten.
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 floating types). String types must only work with other string types. Boolean types are used for decisions.
Assignment Statement
The simplest, and most widely used, statement in Small Basic is the assignment statement. Such a statement appears as:
VariableName = VariableValue
Note that only a single variable can be on the left side of the assignment operator (=). Some simple assignment examples using our “banana” variables:
NumberBananas = 22BananaCost = 0.27IsBananaRotten = "false"MyBananaDescription = "Yes, we have no bananas!"
The actual values assigned to variables here are called literals, since they literally show you their values.
You may recognize the assignment operator as the equal sign used in arithmetic, but it’s not called an equal sign in computer programming. Why is that? Actually, the right side (VariableValue in this example) of the assignment operator is not limited to literals. Any legal Small Basic expression, with any number of variables or other values, can be on the right side of the operator. In such a case, Small Basic computes VariableValue first, then assigns that result to VariableName. This is an important programming concept to remember – “evaulate the right side, assign to the left side.” Let’s start looking at some operators that help in evaluating Small Basic expressions.
Arithmetic Operators
One thing computer programs are very good at is doing arithmetic. They can add, subtract, multiply, and divide numbers very quickly. We need to know how to make our Small Basic programs do arithmetic. There are four arithmetic operators we will use from the Small Basic language.
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 + 8 | 11 |
Subtraction | 6 - 4 | 2 |
Subtraction | 11 - 7 | 4 |
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 * 12 | 24 |
Division | 12 / 2 | 6 |
Division | 42 / 6 | 7 |
I’m sure you’ve done addition, subtraction, multiplication, and division before and understand how each operation works.
What happens if an assignment statement contains more than one arithmetic operator? Does it make any difference? Look at this example:
7 + 3 * 4
What’s the answer? Well, it depends. If you work left to right and add 7 and 3 first, then multiply by 4, the answer is 40. If you multiply 3 times 4 first, then add 7, the answer is 19. Confusing? Well, yes. But, Small Basic takes away the possibility of such confusion by having rules of precedence. This means there is a specific order in which arithmetic operations will be performed. That order is:
- Multiplication (*) and division (/)
- Addition (+) and subtraction (-)
So, in an assignment statement, all multiplications and divisions are done first, then additions and subtractions. In our example (7 + 3 * 4), we see the multiplication will be done before the addition, so the answer provided by Small Basic would be 19.
If two operators have the same precedence level, for example, multiplication and division, the operations are done left to right in the assignment statement. For example:
24 / 2 * 3
The division (24 / 2) is done first yielding a 12, then the multiplication (12 * 3), so the answer is 36. But what if we want to do the multiplication before the division - can that be done? Yes - using the Small Basic grouping operators - parentheses (). By using parentheses in an assignment statement, you force operations within the parentheses to be done first. So, if we rewrite our example as:
24 / (2 * 3)
the multiplication (2 * 3) will be done first yielding 6, then the division (24 / 6), yielding the desired result of 4. You can use as many parentheses as you want, but make sure they are always in pairs - every left parenthesis needs a right parenthesis. If you nest parentheses, that is have one set inside another, evaluation will start with the innermost set of parentheses and move outward. For example, look at:
((2 + 4) * 6) + 7
The addition of 2 and 4 is done first, yielding a 6, which is multiplied by 6, yielding 36. This result is then added to 7, with the final answer being 43. You might also want to use parentheses even if they don’t change precedence. Many times, they are used just to clarify what is going on in an assignment statement.
As you improve your programming skills, make sure you know how each of the arithmetic operators work, what the precedence order is, and how to use parentheses. Always double-check your assignment statements to make sure they are providing the results you want.
Some examples of Small Basic assignment statements with arithmetic operators:
TotalBananaCost = NumberBananas * BananaCostNumberOfWeeks = NumberOfDays / 7AverageScore = (Score1 + Score2 + Score3) / 3.0
Notice a couple of things here. First, notice the parentheses in the AverageScore calculation forces Small Basic to add the three scores before dividing by 3. Also, notice the use of “white space,” spaces separating operators from variables. This is a common practice in Small Basic that helps code be more readable. We’ll see lots and lots of examples of assignment statements as we build programs in this course.
String Concatenation
We can apply arithmetic operators to numerical variables. String variables can also be operated on. Many times in Small Basic programs, you want to take a string variable from one place and ‘tack it on the end’ of another string. The fancy word for this is string concatenation. The concatenation operator is a plus sign (+) and it is easy to use. As an example:
NewString = "Beginning Small Basic " + "is Fun!"
After this statement, the string variable NewString will have the value “Beginning Small Basic is Fun!”.
Notice the string concatenation operator is identical to the addition operator. We always need to insure there is no confusion when using both. String variables are a big part of Small Basic. As you develop as a programmer, you need to become comfortable with strings and working with them.
Comments
You should always follow proper programming rules when writing your Small Basic code. One such rule is to properly comment your code. You can place non-executable statements (ignored by the computer) in your code that explain what you are doing. These comments can be an aid in understanding your code. They also make future changes to your code much easier.
To place a comment in your code, use the comment symbol, a single apostrophe (‘). Anything written after the comment symbol will be ignored by the computer. You can have a comment take up a complete line of Small Basic code, like this:
' Set number of bananasNumberBananas = 14
Or, you can place the comment on the same line as the assignment statement:
NumberBananas = 14 ' Set number of bananas
You, as the programmer, should decide how much you want to comment your code. We will try in the programs provided in this course to provide adequate comments.
Program Output
You’re almost ready to create your first Small Basic program. But, we need one more thing. We have ways to name variables and ways to do math with them, but once we have results, how can those results be displayed? In this class, we will use the method seen in our little Welcome program, the Small Basic WriteLine method that works with the TextWindow object. What this method does is print a string result on a single line:
TextWindow.WriteLine(StringValue)
In this expression, StringValue could be a string variable that has been evaluated somewhere (perhaps using the concatenation operator) or a literal (an actual value). In the Welcome example, we used a literal:
TextWindow.WriteLine("Welcome to Beginning Small Basic!")
And saw that Welcome to Beginning Small Basic! was output to the text window.
What if you want to output numeric information? It’s really quite easy. The WriteLine method will automatically convert a numeric value to a string for output purposes. For example, look at this little code segment:
NumberBananas = 45TextWindow.WriteLine(NumberBananas)
If you run this code, a 45 will appear on the output screen. Go ahead and start Small Basic and try it. This is one fun thing about Small Basic. It is an easy environment to try different ideas.
I started a new program in Small Basic and typed these lines in the editor:
http://msdn.microsoft.com/hh125840.CH03_Img01(en-us,MSDN.10).jpg
When I run this code, I see (I resized the window):
http://msdn.microsoft.com/hh125840.CH03_Img02(en-us,MSDN.10).jpg
You can also combine text information with numeric information using the concatenation operator. For example, this code:
NumberBananas = 45TextWindow.WriteLine("Number of Bananas is " + NumberBananas)
will print Number of Bananas is 45 on the output screen:
http://msdn.microsoft.com/hh125840.CH03_Img03(en-us,MSDN.10).jpg
The numeric data (NumberOfBananas) is converted to a string before it is concatenated with the text data.
So, it’s pretty easy to output text and numeric information. Be aware one slight problem could occasionally arise though. Recall the concatenation operator is identical to the arithmetic addition operator. Look at this little segment of code:
NumberBananas = 32NumberApples = 22TextWindow.WriteLine("Pieces of fruit " + NumberBananas + NumberApples)
You might think you are printing out the total number of fruit (numberBananas + numberApples = 54) with this statement. However, if you run this code, you will get Pieces of fruit 3222:
http://msdn.microsoft.com/hh125840.CH03_Img04(en-us,MSDN.10).jpg
What happens is that Small Basic converts both pieces of numeric data to a string before the addition can be done. Then, the plus sign separating them acts as a concatenation operator yielding the 3222. To print the sum, we need to force the numeric addition by using parentheses:
NumberBananas = 32NumberApples = 22TextWindow.WriteLine("Pieces of fruit " + (NumberBananas + NumberApples))
In this case, the two numeric values are summed before being converted to a string and you will obtain the desired output of Pieces of fruit 54:
http://msdn.microsoft.com/hh125840.CH03_Img05(en-us,MSDN.10).jpg
So, we see the WriteLine method offers an easy-to-use way to output both text and numeric information, but it must be used correctly.
Notice one other thing about this example. The last line of code looks like it’s two lines long! This is solely because of the word wrap feature of the word processor being used. In an actual Small Basic program, this line will appear as, and should be typed as, one single line. Always be aware of this possibility when reading these notes. Let’s build a program.
Program – Sub Sandwich Party
Your family has decided to have a party. Two very long submarine sandwiches are being delivered and it is your job to figure out how much each person can eat. Sure, you could do this with a calculator, but let’s use Small Basic!! This program is saved in the Sandwich folder in the course programs folder (\BeginSB\BSB Code).
Program Design
Assume you know the length of each submarine sandwich. To make the cutting easy, we will say that each person will get a whole number of inches (or centimeters) of sandwich (no decimals). With this information, you can compute how many people can be fed from each sandwich. If the total number is more than the people you have in your family, everyone eats and things are good. If not, you may have to make adjustments. The program steps would be:
- Set a value for the number of inches a person can eat.
- Determine length of both sandwiches.
- Determine how many people can eat from each sandwich.
- Increase or decrease the number of inches until the entire family can eat.
Let’s translate each of these steps into Small Basic code as we build the program. Since this is your first program, we’ll review many steps (creating a new program) and we’ll type and discuss the code one or two lines at a time.
Program Development
Start Small Basic. Click the New Program button in the toolbar. A blank editor will appear. Immediately save the program as Sandwich in a folder of your choice.
First, type the following header information as a multi-line comment and add a title to the text window:
'' Sub Sandwich Program' Beginning Small Basic'TextWindow.Title = "Sub Sandwich Party"
We will use five variables in this program: one for how much each person can eat (InchesPerPerson), two for the sandwich lengths (LengthSandwich1, LengthSandwich2), and two for how many people can eat from each sandwich (Eaters1, Eaters2). These will all be numeric variables. Values for Eaters1 and Eaters2 must be whole numbers since you can’t have a fraction of a family member. Set values for some of the variables (also include a comment about what you are doing):
' set valuesInchesPerPerson = 5LengthSandwich1 = 114LengthSandwich2 = 93
These are just values we made up, you can use anything you like. Notice we assume each person can eat 5 inches of sandwich.
Next, we compute how many people can eat from each sandwich using simple division:
' determine how many people can eat each sandwichEaters1 = Math.Floor(LengthSandwich1 / InchesPerPerson)Eaters2 = Math.Floor(LengthSandwich2 / InchesPerPerson)
We have used something not seen yet – the Math.Floor function. Small Basic provides a Math library that contains a large number of functions for our use (we will look at more of these in the next class). The Math.Floor function returns the whole number part of a decimal number – in this case it insures a whole number person is eating.
Also, notice when you start type the line computing Eaters1, the intellisense drop-down now includes added variables like LengthSandwich1:
http://msdn.microsoft.com/hh125840.CH03_Img06(en-us,MSDN.10).jpg
Display the results using the WriteLine method:
' write resultsTextWindow.WriteLine("Letting each person eat " + InchesPerPerson + " inches")TextWindow.WriteLine((Eaters1 + Eaters2) + " people can eat these two sandwiches!")
Notice how each of the string concatenations works. Notice, too, that we sum the number of people before printing it.
The finished code in Small Basic should look like this:
'' Sub Sandwich Program' Beginning Small Basic' TextWindow.Title = "Sub Sandwich Party"' set valuesInchesPerPerson = 5LengthSandwich1 = 114LengthSandwich2 = 93' determine how many people can eat each sandwichEaters1 = Math.Floor(LengthSandwich1 / InchesPerPerson)Eaters2 = Math.Floor(LengthSandwich2 / InchesPerPerson)' write results' write resultsTextWindow.WriteLine("Letting each person eat " + InchesPerPerson + " inches")TextWindow.WriteLine((Eaters1 + Eaters2) + " people can eat these two sandwiches!")
Double-check to make sure each line is typed properly.
Run the Program
Save your program (click the Save toolbar button). Run your program by clicking the Run toolbar button or it by pressing <F5>. If the program doesn’t run, any errors encountered are listed below the editor. Double-check your code is exact – no misspellings, no missing quotes, no missing punctuation. When it runs, the text window should show this:
http://msdn.microsoft.com/hh125840.CH03_Img07(en-us,MSDN.10).jpg
This says 40 people can eat from this particular set of sandwiches. Congratulations – you have written your very first Small Basic program!!
Other Things to Try
For each program in this course, we will offer suggestions for changes you can make and try. In this above run, we saw 40 people can eat. What if you need to feed more or less? Adjust the InchesPerPerson variable and determine the numbers of people who can eat for each value. After each adjustment, you will need to rerun the program. Assume the sandwiches cost so much per inch. Modify the program so it also computes the cost of the sandwiches. Determine how much each person would have to contribute to pay for their lunch. Give it a try!
Since we require each person to eat an whole number of inches, there might be leftover amounts in each sandwich. Can you figure out how to compute this amount? It’s a neat little application of the Remainder function (returns the remainder when two whole numbers are divided) in the Math library. There are just a couple of code modifications. A new variable InchesLeftOver will be used to compute the leftover amount. Now, the code that computes that value:
' compute leftovers InchesLeftOver = Math.Remainder(LengthSandwich1, InchesPerPerson) + Math.Remainder(LengthSandwich2, InchesPerPerson) TextWindow.WriteLine("There are " + InchesLeftOver + " inches left over.")
Add this code to your program and rerun. Do you see that there are a total of 7 inches remaining?
http://msdn.microsoft.com/hh125840.CH03_Img08(en-us,MSDN.10).jpg
Can you see why in computing InchesLeftOver, we just don’t add both sandwiches length together before using the remainder operator?
Summary
Again, congratulations are due for completing your first Small Basic program. You learned a lot about the Small Basic statements and assignments and how to do a little bit of arithmetic. You should be comfortable with starting a new program with Small Basic. In subsequent classes, we’ll learn a little more Small Basic and write increasingly more detailed Small Basic programs.
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.