Beginning Microsoft Small Basic
Beginning Microsoft Small Basic
Beginning Microsoft Small Basic
Kidware Software
PO Box 701
Maple Valley, WA 98038
http://www.computerscienceforkids.com
http://www.kidwaresoftware.com
Copyright 2010 by Philip Conrod & Lou Tylee. All rights reserved
Kidware Software
PO Box 701
Maple Valley, Washington 98038
1.425.413.1185
www.kidwaresoftware.com
www.computerscienceforkids.com
www.biblebytebooks.com
All Rights Reserved. No part of the contents of this book may be reproduced or transmitted in any form or
by any means without the written permission of the publisher.
Printed in the United States of America
ISBN-13: 978-1-937161-19-4
Book Cover Illustration by Kevin Brockschmidt
Copy Editor: Stephanie Conrod
This copy of the Beginning Microsoft Small Basic book and the associated software is
licensed to a single user. Copies of the course are not to be distributed or provided to any
other user. Multiple copy licenses are available for educational institutions. Please
contact Kidware Software for school site license information.
This guide was developed for the course, Beginning Microsoft Small Basic, produced
by Kidware Software, Maple Valley, Washington. It is not intended to be a complete
reference to the Small Basic language. Please consult the Microsoft website for detailed
reference information.
This guide refers to several software and hardware products by their trade names. These
references are for informational purposes only and all trademarks are the property of their
respective companies and owners.
Microsoft, Visual Studio, Small Basic, Visual Basic, Visual J#, and Visual C#,
IntelliSense, Word, Excel, MSDN, and Windows are all trademark products of the
Microsoft Corporation.
Java is a trademark product of the Sun Corporation. JCreator is a trademark product of
XINOX Software
The example companies, organizations, products, domain names, e-mail addresses, logos,
people, places, and events depicted are fictitious. No association with any real company,
organization, product, domain name, e-mail address, logo, person, place, or event is
intended or should be inferred.
This book expresses the authors views and opinions. The information in this book is
distributed on an "as is" basis, without and expresses, statutory, or implied warranties.
Neither the author(s) nor Kidware Software, LLC shall have any liability to any person or
entity with respect to any loss nor damage caused or alleged to be caused directly or
indirectly by the information contained in this book.
Philip Conrod has been programming computers since 1978. Since then, he has
authored, co-authored and edited many beginning computer programming
tutorials and books for kids, teens and adults. Philip also holds a BS in
Computer Information Systems and a Master's certificate in the Essentials of
Business Development from Regis University. Philip has also held various
Information Technology leadership roles in companies like Sundstrand
Aerospace, Safeco Insurance Companies, FamilyLife, Kenworth Truck Company,
and PACCAR. Today, Philip serves as the Chief Information Officer for a large
manufacturing company based in Seattle, Washington. In his spare time, Philip
serves as the President of Kidware Software, LLC. He makes his home with his
lovely wife and three beautiful and techie daughters in Maple Valley,
Washington.
Acknowledgements
I would like to thank my beautiful wife, Tiffany, for sacrificing so many nights and
weekends so I could finish and publish this edition of the book. I also want to
thank my three wonderful daughters - Stephanie, Jessica and Chloe, who helped
with various aspects of the book publishing process including software testing,
book editing, creative design and many other more tedious tasks like finding all my
errors. I could not have accomplished this without all your hard work, love and
support. I also want to thank my very talented illustrator, Kevin Brockschmidt ,
who designed the book cover and the Computer Science Kids. Kevin was very
generous with his time and creative talents. Many thanks to others who worked
behind the scenes like Jack Barrow and Harold Coqmard for helping me out at the
last minute when I just could not figure out Adobe Acrobat and Adobe Illustrator. I
also want to thank Rajesh Tuteja for helping me with language translation and
some other important behind the scenes tutorial work.
Last but definitely not least, I want to thank my multi-talented co-author, Lou
Tylee, for doing all the real hard work necessary to develop, test, debug, and
keep current all the kid-friendly applications, games and base tutorial text found in
this book. Lou has tirelessly poured his heart and soul into so many previous
versions of this tutorial and there are so many beginners who have benefited from
his work over the years. Lou is by far one of the best application developers and
tutorial writers I have ever worked with. Thanks Lou for collaborating with me on
this book project.
Table of Contents
1. Introducing Small Basic
Preview ......................................................................................................1-1
Why Learn Small Basic? ............................................................................ 1-2
A Brief History of Small Basic ....................................................................1-4
Lets Get Started ...................................................................................... 1-10
Downloading and Installing Small Basic................................................... 1-12
Starting Small Basic ................................................................................. 1-16
Opening a Small Basic Program .............................................................. 1-19
Running a Small Basic Program .............................................................. 1-21
Stopping Small Basic ............................................................................... 1-23
Summary ................................................................................................. 1-24
Introduction
Microsoft Small Basic is a wonderful programming environment for beginners.
Small Basic is very easy and approachable for both kids and adults. The aim of
this book is to teach you the fundamentals of programming with Microsoft Small
Basic by using the free Microsoft Small Basic Development Environment. You will
learn the features of the Small Basic language, and then use them to build
applications running on the Microsoft Windows operating system. Beginning
Microsoft Small Basic consists of 11 chapters explaining (in simple, easy-to-follow
terms) how to build a Small Basic application. You learn about program design,
text window applications, graphics window applications and many elements of the
Small Basic language. Numerous examples are used to demonstrate every step in
the building process. The tutorial also includes several detailed computer
programs to illustrate the fun of Small Basic.
Beginning Microsoft Small Basic is presented using a combination of over 400
pages of course notes and actual Small Basic examples. In the final chapter, we
list out three classic computer games that were originally published by David H.
Ahl, the founder of Creative Computing Magazine. We list the source code to
each of these games in Microsoft Small Basic, Visual Basic, Visual C#, Java, and
BASIC. This allows you to easily compare and contrast the Small Basic source
code against several different computer programming languages that you may or
may not know. If you are new to programming this will help you understand how
these games would be developed in another more sophisticated programming
language. BibleByte Books also produces beginning programming tutorials for
several other programming languages like Visual Basic, Visual C#, and Java.
Please visit our website for more information on our beginning programming
tutorials: http://www.computerscienceforkids.com. If you are learning Microsoft
Small Basic after learning a different programming language, the final chapter of
this tutorial can help you leverage your existing programming knowledge in that
System Requirements
You will need the following hardware and software to complete the exercises in
this book:
The BSB Notes folder includes all the notes needed for the class. Each file in this
folder has a DOC extension and is in Microsoft Word format. We also provide the
associated .doc files in an Adobe .PDF file format, if you dont have Microsoft
Word available on your computer. The files are the following:
StartHere.doc
Class2.doc
Class3.doc
Class4.doc
Class5.doc
Class6.doc
Class7.doc
Class8.doc
Class9.doc
Course Prerequisites:
To use the Beginning Microsoft Small Basic Programming Tutorial, you should be
comfortable working within the Windows (or other operating system) environment,
knowing how to find files, move windows, resize windows, etc. No programming
experience is needed. You will also need the ability to view and print documents
saved in Microsoft Word format. This can be accomplished in one of three ways.
The first, and easiest, is that you already have Microsoft Word (or a compatible
equivalent) on your computer. The second way is that you can download the
Microsoft Word Viewer. This is a free Microsoft product that allows viewing and
printing Word documents - it is available for download at all the major shareware
internet sites and from our website.
Finally, and most obvious, you need to have Microsoft Small Basic. This is a
FREE product that can be downloaded from the Microsoft Small Basic website:
http://www.smallbasic.com
1-1
Preview
You are about to start a new journey. Writing programs that ask a
computer to do certain tasks is fun and rewarding. Like any journey, you need to
prepare before starting. In this first class, we do that preparation. You will learn
why you might want to learn Small Basic. You will see the historical lineage of
Small Basic. You will download and install the Small Basic development software
that will help you create Small Basic programs. Once the preparation is done, you
will run your first Small Basic application to check that you have prepared properly.
Lets get started.
1-2
We could very well just ask the question Why Learn a Programming
Language? A programming language is used to provide instructions to a
computer to do specific tasks. There are several reasons for doing this. First, if
you know how to program, you will have a better understanding of just how
computers work. Second, writing programs is good exercise for your thinking skills
you must be a very logical thinker to write computer programs. You must also
be something of a perfectionist computers are not that smart and require exact,
perfect instructions to do their jobs. Third, computer programmers are in demand
and you can make a good living. And, last, writing computer programs is fun. Its
rewarding to see your ideas for a certain computer program come to life on the
computer screen.
So, why learn Small Basic? One big reason is that its free from Microsoft.
Another reason for learning Small Basic is that it is one of the easiest languages to
learn. Small Basic is a simple language. There are many built-in elements that
make your work simpler and the language itself is very simple only 15 reserved
keywords. But, just because it is a simple language doesnt mean it lacks
capabilities. You will see throughout these notes that you can build some fairly
complex programs.
Because of its simplicity, you can learn to write Small Basic programs very
quickly. But, just because you can write your first program quickly doesnt mean
youll learn everything there is to know about Small Basic. This course just
introduces Small Basic. Theres still a lot to learn theres always a lot to learn.
So, consider this course as a first step in a journey to becoming a proficient
computer programmer.
1-3
And, once youve mastered Small Basic, you can graduate to its more
capable big brother Visual Basic, another Microsoft product used to develop GUI
(graphical user interface) based applications. These are applications with menus,
toolbars, buttons, scroll bars, and other controls which depend on the computer
mouse for input. Examples of GUI applications you may have used are word
processors, spreadsheet programs and computer games.
1-4
1-5
On the cover is an Altair 8800 computer. It must have been really expensive
note the Save Over $1000 line. About all the computer could do was flash some
lights according to a program written by the user. But, it was the first home
1-6
computer. Bill Gates and Paul Allen saw the potential. They developed a BASIC
language for the Altair computer and marketed it through their new company
Microsoft. Yes, the first product sold by Microsoft was the BASIC computer
language. It sold for $350 and was distributed on a cassette tape.
Then, in the late 1970s and early 1980s, it seems there were computers
everywhere with names like Radio Shack TRS-80, Commodore 64, Texas
Instruments 99/4A, Atari 400, Coleco Adam, Timex Sinclair and the IBM PC-Jr.
Stores like Sears, JC Penneys and even K Mart sold computers. One thing all
these machines had in common was that they were all programmed in some
version of Microsofts BASIC. Each computer had its own fans and its own
magazines. Computer users would wait each month for the next issue of a
magazine with BASIC programs you could type into your computer and try at
home. My computer of choice at that time was the TRS-80 Color Computer:
Like Microsofts first product, our BIBLEBYTES programs were distributed on audio
cassette tapes.
This was a fun and exciting time for the beginning programmer, but the fun
times ended with the introduction of the IBM-PC in the early 1980s. Bigger and
1-7
Basic, which I would call a close relative of the early, original BASIC language.
Small Basic was developed by Vijaye Raji, a developer at Microsoft, in 2008 in
response to an article written in September 2006 by David Brin called, Why
Johnny cant code. It would be best to let Vijaye tell the story of how Small Basic
was born. The following Small Basic History was copied from Vijayes Blog dated
October 23, 2008 entitled Hello World.
It all happened in August of 2007 when someone sent me a pointer
to the article Why Johnny Can't Code and it got me thinking. After all, when
I was a kid, I started programming in ZX Spectrum with a built in Sinclair
BASIC interpreter and did so until I ran into Turbo BASIC. To me that
transformation was groundbreaking and was the single most important
reason why I chose to write software for a living, for the rest of my life.
An informal poll along the corridors in Microsoft revealed that most
developers within Microsoft had started programming in some variant of
BASIC. It had all the good characteristics of a good beginner programming
language - simplicity, minimal ceremony, instant gratification and ubiquity.
It helped them "get" programming and assisted them with understanding
the need for more advanced concepts.
When I asked them how they're going to teach programming to their
children, they were stumped. Almost everyone wanted to, they just didn't
know how. Some said KPL, Python and Ruby. Some said Alice and
Scratch. But they all felt that none of these have the charm of BASIC. Of
course there were some that took the Dijkstra's stand, but they were few.
1-8
1-9
1-10
You should know how to start your computer and use the mouse.
You should know how to resize and move windows around on the screen.
You should know how to run an application on your computer by using the
Start Menu or some other means.
You should know how to fill in information in dialog boxes that may pop up
on the screen.
You should know about folders and files and how to create and find them
on your computer.
You should know what file extensions are and how to identify them. For
example, in a file named Example.ext, the three letters ext are called the
extension.
You should know how to click on links to read documents and move from
page to page in such documents. You do this all the time when you use
the Internet.
You should know how to access the Internet and download files.
1-11
You have probably used all of these skills if youve ever used a word
processor, spreadsheet, or any other software on your computer. If you think you
lack any of these skills, ask someone for help. They should be able to show you
how to do them in just a few minutes. Actually, any time you feel stuck while trying
to learn this material, never be afraid to ask someone for help. We were all
beginners at one time and people really like helping you learn.
Lets get going. And, as we said, were going to take it slow. In this first
class, we will learn how to install Small Basic and its documentation on your
computer, how to load a Small Basic program, how to run the program, and how to
stop the program. It will be a good introduction to the many new things we will
learn in the classes to come.
Note: At this writing, Microsoft was offering Version 0.8 of Small Basic.
That is the version used in these notes.
.
1-12
To write and run programs using Small Basic, you need the Small Basic
program. This is a free product that you can download from the Internet. This
simply means we will copy a file onto our computer to allow installation of Small
Basic.
Start up your web browser (Internet Explorer, Netscape or other). Small
Basic is hosted at Kids Corner in Microsofts Beginner Development Learning
Center:
http://www.smallbasic.com
This web site has lots of useful programming information. As you become more
proficient in your programming skills, you will go to this site often for answers to
programming questions, interaction with other programmers, and lots of sample
programs. Though its hosted at a kid site, Small Basic is appropriate for all ages.
On the Small Basic web page, you should see a button that allows to
download Small Basic:
1-13
1-14
1-15
Click Next to start the installation process. Accept the licensing agreement. Then,
for each screen afterwards, accept the default choice by clicking Next. When
done you should see a screen announcing a successful installation.
1-16
Well learn how to start Small Basic, how to load a Small Basic program,
and how to run a program. This will give us some assurance we have everything
installed correctly. This will let us begin our study of the Small Basic programming
language.
Once installed, to start Small Basic:
(Some of the headings given here may differ slightly on your computer, but you
should have no trouble finding the correct ones.) The Small Basic program should
start. Several windows will appear on the screen.
After installation and trying to start, you may see an error message that
announces Small Basic cannot be started. If this occurs, try downloading and
installing the latest version of the Microsoft .NET framework at:
http://msdn.microsoft.com/en-us/netframework/aa569263.aspx
This contains some files that Small Basic needs to operate and such files may not
be on your computer.
1-17
Toolbar
Help
Editor
1-18
most of our tasks. In the middle of the screen is the Editor. This is where we will
write our Small Basic programs. To the right is a Help area. Small Basic has
great help features when writing programs. This area will display hints and tips
while we write code.
1-19
1-20
Find and open the folder named BSB Code. This folder holds all the
programs for the course
Remember how you got to this folder. Throughout the course, you will go to this
folder to open programs you will need. Open the program folder named
Welcome. Note there is one file in Welcome named Welcome. Select that file
and click Open.
This should appear in the Small Basic editor:
You now finally see your first Small Basic program: Well learn what these few
lines of code do in the next class. Right now, we just want to see if we can get this
program running.
1-21
After developing a Small Basic program, you want to start or run the
program. This gets the program started and allows the computer do its assigned
tasks. We can also run a program also using the toolbar. Look for a button that
looks like the Play button on a VCR, CD player, or cassette tape player:
Run Program
Toolbar Button
Click this button to run the Welcome program (the program we opened
previously).
You can also run a program by pressing the <F5> function key.
1-22
message:
If youve gotten this far, everything has been installed correctly. If you dont see
the Welcome message, something has not been installed correctly. You should
probably go back and review all the steps involved with installing Small Basic and
Small Basic and make sure all steps were followed properly.
To stop this program, press any key or click the boxed X in the upper right
corner of the window.
1-23
Its been a lot of work just to get to this point. We finally have our first Small
Basic program running and now were just going to stop it and move on. Well dig
into many more details in Class 2.
When you are done working with a Small Basic program, you want to leave
the Small Basic environment. To stop Small Basic, click on the close button in the
upper right hand corner of the main window. Its the button that looks like an X.
Stop Small Basic now. Small Basic will close all open windows and you will be
returned to the Windows desktop. You may be asked if you would like to save the
program modifications (in case any were made):
If you are asked such a question, answer No so the Welcome program remains
unchanged.
1-24
Summary
We covered a lot of new material here. As we said earlier, you learned a lot
of new words and concepts. Dont worry if you dont remember everything we
talked about here. You will see the material many times again. Its important that
you just have some concept of what goes into a Small Basic program. You also
know how to start and stop the Small Basic environment.
In summary, we installed the Small Basic environment. Using Small Basic,
we learned how to open a Small Basic program. We learned how to run a
program. In the next class, you will learn (in detail) what each of these steps really
means. And, you will begin to acquire the skills that allow you to start building
your own Small Basic program. Using the Welcome program as an example, you
will learn about important concepts related to a Small Basic program. Then, in
Class 3, you will actually build your first program!
2-1
In the first class, we spent all of our time just preparing our computer for
creating and running Small Basic programs. In this second class, we will look
further into some of the tasks we have done. We will reexamine the Welcome
program from Class 1. We will learn some of the basic rules for writing Small
Basic programs. We will create and save a program using Small Basic. This will
give us the skills needed to create our first Small Basic program in Class 3.
2-2
Start Small Basic and open the Welcome program we looked at in Class 1
Heres the code you will see in the editor:
'
'WelcomeProgram
'BeginningSmallBasic
'
TextWindow.Title="WelcomeProgram"
TextWindow.WriteLine("WelcometoBeginningSmallBasic!")
A program is made up of many statements. Every line is a statement and every
statement instructs the computer to do something.. Lets go through this code line
by line to explain its structure and see what each line does.
The first several lines of the program are:
'
'WelcomeProgram
'BeginningSmallBasic
'
These lines are comments. They simply provide some information about what
the program is and provides some contact information. The comment begins with
a single apostrophe (). These lines are also known as a program header. Its a
good idea to always put a header on your Small Basic programs to give someone
an idea of what your program does and who wrote it. When running a program,
Small Basic ignores any comments their only use is provide explanation.
2-3
Notice the words Welcome Program in the title bar of the window. The above line
of code displays that title. In this line, TextWindow is an object built into Small
Basic it is the window that displays the output of the program. Small Basic has a
number of such objects available for our use. We will use the TextWindow object
extensively in our first few programs. Objects have both properties and
methods. Properties describe objects, while methods do things to objects. In this
single line of code, we are setting the Title property of the TextWindow object to
the text string Welcome Program. The dot (.) and assignment operator (=) are
punctuations that must be placed appropriately for the computer to understand
your intent. This line of code literally says set the Title property of the
TextWindow object to Welcome Program.
2-4
TextWindow.WriteLine("WelcometoBeginningSmallBasic!")
Notice in the text window of the running program, there is a message that says
Welcome to Beginning Small Basic! . The above line of code printed that
message. This line of code uses the TextWindow WriteLine method to perform
the task. We say the text Welcome to Beginning Small Basic! is passed to the
WriteLine method the input is placed in parentheses which then results in the
input text being written in the text window.
Though this is a very short, very simple program, it illustrates some major
components in a Small Basic program. We want a program header and
appropriate comments. Using properties and methods, we can display information
using the built-in Small Basic object, the TextWindow.
2-5
Lets look at the Welcome code one more time to point out some basic
rules of Small Basic programming. Heres that code:
'
'WelcomeProgram
'BeginningSmallBasic
'
TextWindow.Title="WelcomeProgram"
TextWindow.WriteLine("WelcometoBeginningSmallBasic!")
And, heres the rules:
Small Basic is not case-sensitive, meaning upper and lower case letters are
considered to be the same characters. That means writeline and
WriteLine are the same. But, even though Small Basic is not casesensitive, it is good practice to use accepted case conventions in
programming.
Small Basic ignores any white space such as blanks. We will often use
white space to make our code more readable to humans.
2-6
2-7
In Class 3, we will begin learning the Small Basic language and start writing
our own Small Basic programs. In preparation for this, youll need to know how to
create a new program with Small Basic. Lets do that now. What well do is recreate the Welcome program.
If its not already running, start Small Basic. Click the New Program
button in the toolbar:
New Program
Toolbar Button
Click in this window and start typing in the code for the Welcome program.
2-8
shown (pay attention to the rules seen earlier). After each line, press the <Enter>
key. Here, again, is the code.
'
'WelcomeProgram
'BeginningSmallBasic
'
TextWindow.Title="WelcomeProgram"
TextWindow.WriteLine("WelcometoBeginningSmallBasic!")
After typing the four comment lines and starting to type the first line of code you
will notice this popup appears:
Small Basic has a feature called intellisense that helps you type your programs
faster. When this list appears, you move through the list using the up/down arrow
keys and make a selection by pressing <Enter>. It will appear for object names,
properties and methods. Give it a try!
2-9
Also notice as soon as you type TextWindow, this appears in the help area
of the Small Basic environment:
Small Basic provides context-sensitive help. The help area will always display
information it deems is important to the user at the appropriate time. In this case,
information concerning the properties (marked by painters palette icon) and
methods (marked by gear icon) for the TextWindow object are displayed. And,
once you select a property or method, a help description for that selection
2-10
appears. For example, once you type Title, you will see this help screen
describing the property and how its used:
With intellisense and context-sensitive help, you always have on-line information
to help you with your programming tasks.
Notice these editing buttons in the toolbar:
If youve ever used a word processor, these tasks are familiar to you. When typing
code, you can Cut, Copy and Paste. And you can Undo and Redo tasks. These
tasks make typing code (especially long programs) much easier in the Small Basic
environment. Another thing to notice is that the editor uses different colors for
different things in the code. Comments, objects, method names and data used by
objects are all colored differently. This coloring sometimes helps you identify
mistakes you may have made in typing.
2-11
Try running your program. Use the toolbar run program button (or press <F5>).
You should once again see the Welcome to Beginning Small Basic! Message:
You should also see that its really kind of easy to get a Small Basic program up
and running.
2-12
Create the folder you want to save the program in. In this example, I have created
a folder named Welcome in a MySmallBasic folder.
2-13
Click Save and the program is saved. From this point on, whenever you reopen
this program and make modifications, if you click the Save toolbar button, the
program will be automatically saved with the same name in the same folder. We
suggest you do this occasionally while modifying a program.
2-14
Use the resulting dialog boxes to name and locate your program.
If you try to exit Small Basic and have not saved programs, Small Basic will
pop up a dialog box to inform you of such and give you an opportunity to save files
before exiting. An example dialog is:
Make the appropriate choice. Click Yes to save your program if you want to
keep the changes you have made to it.
2-15
When you save a Small Basic program in a particular folder, files other than
the file listing your code are saved. These files are needed by the Small Basic
environment to keep track of things.
Using My Computer or Windows Explorer in Windows, go to the folder
containing the Welcome program you just built and ran. You should see the
following files:
The file named Welcome with type Small Basic Program is the source code that
appears in the editor of Small Basic. The Welcome file marked Application is a
compiled version of the code and is the executable code. If you double-click this
file, the Welcome program will run independent of the Small Basic environment.
Try it if you like. Later we will learn how to use this file to let your friends run your
programs on their computers or even on the Internet! The Welcome.pdb file is a
database file with information needed by your program and lastly,
SmallBasicLibrary.dll is called a run-time library. It contains files that help your
program run.
We describe these files so you are aware of their presence. Do not modify
or delete any of these files outside of the Small Basic environment.
2-16
Summary
After all the downloading and installing done in the first class, this second
class must have seemed like a breeze. In this class, we looked at several
important concepts that will let us start building our own Small Basic programs.
In this class, we studied the structure of a program, knowing it is built using
objects, properties and methods. We learned how to use Small Basic to create
and run a new program. We looked briefly at some of the rules used in writing
Small Basic code and we saw how to save a program. In the next class, we finally
get started learning the Small Basic language. And, well write and run our first
Small Basic program.
3-1
In the first two classes, youve 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.
3-2
Recall 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.
Its 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, heres two
numbers add them together and tell me the sum. A human might understand
these instructions, but a computer wont. 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:
1. Give a value to the first number.
2. Give a value to the second number.
3. Add the first number to the second number, resulting in the sum, a third
number.
4. 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 computers language. And, in
this course, the computers 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
3-3
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
theyre 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. Lets
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:
1. Determine the score of each student.
2. Add up the 352 scores to get a sum.
3. Divide the sum by 352 to get the average value.
4. 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:
1. Start with the first score.
2. Add in the second score, then the third score, then the fourth score, etc.
3. 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.
3-4
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 players 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:
1. Shuffle a deck of cards.
2. Give a card to the first player.
3. Give a card to the second player.
4. Determine which card is higher and declare a winner.
5. 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 its 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.
3-5
If all of these concepts are not clear at the moment, thats 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 its 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. Well start
slow. By the end of this course, you should be pretty good at talking Small
Basic.
3-6
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.
3-7
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).
You cannot use a word reserved by Small Basic (for example, you cant
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
BananaCost
NumberBananas
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.
3-8
Variable Types
-20
4000
Notice you write 4,000 as 4000 in Small Basic we cant 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
3-9
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 its 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 computers
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.
3-10
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=22
BananaCost=0.27
IsBananaRotten="false"
MyBananaDescription="Yes,wehavenobananas!"
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 its 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. Lets start looking at some
operators that help in evaluating Small Basic expressions.
3-11
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
Addition
3+8
11
Subtraction
6-4
Subtraction
11 - 7
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
Division
42 / 6
Im sure youve done addition, subtraction, multiplication, and division before and
understand how each operation works.
3-12
3-13
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 dont 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*BananaCost
NumberOfWeeks=NumberOfDays/7
AverageScore=(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
3-14
is a common practice in Small Basic that helps code be more readable. Well see
lots and lots of examples of assignment statements as we build programs in this
course.
3-15
String Concatenation
NewString="BeginningSmallBasic"+"isFun!"
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.
3-16
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:
'Setnumberofbananas
NumberBananas=14
Or, you can place the comment on the same line as the assignment statement:
NumberBananas=14'Setnumberofbananas
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.
3-17
Program Output
Youre 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("WelcometoBeginningSmallBasic!")
And saw that Welcome to Beginning Small Basic! was output to the text
window.
What if you want to output numeric information? Its 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=45
TextWindow.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.
3-18
You can also combine text information with numeric information using the
concatenation operator. For example, this code:
NumberBananas=45
TextWindow.WriteLine("NumberofBananasis"+NumberBananas)
will print Number of Bananas is 45 on the output screen:
3-19
So, its 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=32
NumberApples=22
TextWindow.WriteLine("Piecesoffruit"+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:
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=32
NumberApples=22
TextWindow.WriteLine("Piecesoffruit"+(NumberBananas+
NumberApples))
3-20
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:
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
its 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. Lets build a program.
3-21
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 lets 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:
1. Set a value for the number of inches a person can eat.
2. Determine length of both sandwiches.
3. Determine how many people can eat from each sandwich.
4. Increase or decrease the number of inches until the entire family can eat.
Lets translate each of these steps into Small Basic code as we build the program.
Since this is your first program, well review many steps (creating a new program)
and well type and discuss the code one or two lines at a time.
3-22
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:
'
'SubSandwichProgram
'BeginningSmallBasic
'
TextWindow.Title="SubSandwichParty"
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 cant have a fraction of a family
member. Set values for some of the variables (also include a comment about
what you are doing):
'setvalues
InchesPerPerson=5
LengthSandwich1=114
LengthSandwich2=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.
3-23
Next, we compute how many people can eat from each sandwich using
simple division:
'determinehowmanypeoplecaneateachsandwich
Eaters1=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:
'writeresults
TextWindow.WriteLine("Lettingeachpersoneat"+InchesPerPerson
+"inches")
TextWindow.WriteLine((Eaters1+Eaters2)+"peoplecaneatthese
twosandwiches!")
Notice how each of the string concatenations works. Notice, too, that we sum the
number of people before printing it.
3-24
'
'SubSandwichProgram
'BeginningSmallBasic
'
TextWindow.Title="SubSandwichParty"
'setvalues
InchesPerPerson=5
LengthSandwich1=114
LengthSandwich2=93
'determinehowmanypeoplecaneateachsandwich
Eaters1=Math.Floor(LengthSandwich1/InchesPerPerson)
Eaters2=Math.Floor(LengthSandwich2/InchesPerPerson)
'writeresults'writeresults
TextWindow.WriteLine("Lettingeachpersoneat"+InchesPerPerson
+"inches")
TextWindow.WriteLine((Eaters1+Eaters2)+"peoplecaneatthese
twosandwiches!")
Double-check to make sure each line is typed properly.
3-25
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 doesnt 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:
This says 40 people can eat from this particular set of sandwiches.
Congratulations you have written your very first Small Basic program!!
3-26
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? Its 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:
'computeleftovers
InchesLeftOver=Math.Remainder(LengthSandwich1,InchesPerPerson)
+Math.Remainder(LengthSandwich2,InchesPerPerson)
TextWindow.WriteLine("Thereare"+InchesLeftOver+"inchesleft
over.")
3-27
Add this code to your program and rerun. Do you see that there are a total of 7
inches remaining?
Can you see why in computing InchesLeftOver, we just dont add both
sandwiches length together before using the remainder operator?
3-28
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, well learn a little more
Small Basic and write increasingly more detailed Small Basic programs.
4-1
You should now be fairly comfortable with creating and running simple
Small Basic programs. In this class, we continue learning new Small Basic topics
to expand our programming knowledge. We'll look at some program design ideas,
some mathematical functions and at ways to get input from users of your
programs. And, we'll build a savings calculator program.
4-2
Program Design
You are about to start developing fairly detailed programs using Small
Basic. We will give you programs to build and maybe you will have ideas for your
own programs. Either way, its fun and exciting to see ideas end up as computer
programs. But before starting a program, its a good idea to spend a little time
thinking about what you are trying to do. This idea of proper program design will
save you lots of time and result in a far better program.
Proper program design is not really difficult. The main idea is to create a
program that is easy to use, easy to understand, and free of errors. That makes
sense, doesnt it? Spend some time thinking about everything you want your
program to do. What information does the program need? What information does
the computer determine? Decide what programming steps you need to follow to
accomplish desired tasks.
Make the Small Basic code in your methods readable and easy to
understand. This will make the job of making later changes (and you will make
changes) much easier. Follow accepted programming rules - you will learn these
rules as you learn more about Small Basic. Make sure there are no errors in your
program. This may seem like an obvious statement, but many programs are not
error-free.
The importance of these few statements about program design might not
make a lot of sense right now, but they will. The simple idea is to make a useful,
clearly written, error-free program that is easy to use and easy to change.
Planning carefully and planning ahead helps you achieve this goal. For each
program built in this course, we will attempt to give you some insight into the
program design process. We will always try to explain why we do what we do in
building a program. And, we will always try to list all the considerations we make.
4-3
4-4
We covered a lot of Small Basic in the last class. This was necessary to
introduce you to many basic concepts so you could write your first program. In
this briefer second lesson, we look at some mathematical functions.
Mathematical Functions
In Class 3, we saw the Small Basic arithmetic operators that allow us to
perform the basics of addition, subtraction, multiplication and division. Like other
computer programming languages, Small Basic also has the capability of doing
very power mathematical computations. Small Basics built-in mathematical
functions (also called methods) are often used in these computations. We used
a couple of these functions in the Sub Sandwich program (Math.Floor and
Math.Remainder)
We dont expect you to be a mathematical genius to work through these
notes, so we will only look at three mathematical functions. First, just what is a
function? A function is a routine that computes some value for you, given some
information. The format for using a function is:
FunctionValue=FunctionName(ArgumentList)
FunctionName is the name of the function and ArgumentList is a list of values
(inputs, separated by commas) provided to the function so it can do its work. In
this assignment statement, FunctionName uses the values in ArgumentList to
compute a result and assign that result to the variable we have named
FunctionValue.
4-5
How do you know what Small Basic mathematical functions exist, what type
of information they provide and what the arguments are? Check various Small
Basic references and the Microsoft Small Basic website. Or, just type the word
Math in the Small Basic code window and the help area will display all the
functions:
4-6
Then, choose a function name and the help window will tell you how to use it.
Here is information on the first function we look at (Abs):
4-7
The first function we examine is the absolute value function. In math, the
absolute value is the positive part of a number. The Small Basic function is:
Math.Abs(Argument)
where argument is number we want the absolute value of. The argument can be
either an int or double type and the returned value will be the same type as the
argument. Some examples:
Example
Result
Math.Abs(7)
Math.Abs(11)
11
Math.Abs(3.14)
3.14
Math.Abs(72.1)
72.1
Have you ever needed the square root of a number? A square root is a
number that when multiplied by itself gives you the original number. For example,
the square root of 4 is 2, since 2 times 2 is four. Theres a button on your
calculator () that will do this for you. In Small Basic, the square root function is:
Math.SquareRoot(Argument)
where Argument is number we want the square root of. The argument must be a
non-negative number. Some examples:
Example
Result
Math.SquareRoot(4)
Math.SquareRoot(36)
Math.SquareRoot(72.1) 8.491
4-8
Result
Math.Power(4,2)
16
Math.Power(3,3)
-27
Math.Power(10,2)
10000
In each example here, the arguments have no decimal parts. We have done this
to make the examples clear. You are not limited to such values. It is possible to
use this function to compute what happens if you multiply 7.654 times itself 3.16
times!! (The answer is 620.99, by the way.)
For the more mathematically inclined reader, you should know that there
are many more Small Basic functions available for your use. You might want to
look into using them. There are trigonometric functions and inverse trig functions,
functions to convert from radians to degrees and vice versa, functions to find
extreme values, functions for rounding, logarithm and inverse logarithm functions
and a built-in value for pi. (If none of this means anything to you, dont worry we
wont be using them in this class).
4-9
4-10
Start Small Basic. Click the New Program button in the toolbar. A blank
editor will appear. Immediately save the program as InputExample in a folder of
your choice. Type these lines in the editor
TextWindow.WriteLine("Whatisyourage?")
UserAge=TextWindow.ReadNumber()
TextWindow.WriteLine("Youinput"+UserAge)
In this code, we ask for a user to input their age, then write it in the text window.
Run the program (click the Run button or press <F5>). You should see:
Notice how the prompt appears. Type in a value and press <Enter>. Once the
number is input, it is assigned to the variable UserAge and the WriteLine method
displays the entered value:
4-11
Notice the input value appears on a separate line after the prompting
question. Most times, you would like this value to be on the same line as the
prompt. This can be done by using a different TextWindow method. The
WriteLine method appends a new line character to the output text, hence
subsequent information goes to that new line. The Write method does not begin a
new line. Modify the first line of code with the shaded changes (change the
WriteLine method to Write and add a space after the question mark):
TextWindow.Write("Whatisyourage?")
Rerun the program. Now when you type your age, it appears next to the
prompting question:
Run the program again and try to enter non-numeric characters you wont be
able to. The ReadNumber method only accepts numeric data (the digits 0
through 9, a leading minus sign, or a single decimal point).
4-12
lines of code that ask for a users name in a manner similar to requesting the age:
TextWindow.Write("Whatisyourname?")
UserName=TextWindow.Read()
TextWindow.WriteLine("Youinput"+UserName)
Run the program again. Type your age, press <Enter> and you will see the
prompt asking for your name:
Enter a string (any characters at all can be typed) and press <Enter> to see:
4-13
It seems the input methods are working just fine. Did you notice how
building a program in stages (adding a few lines of code at a time) is good?
Always follow such a procedure. Before leaving this example and building another
program, lets take a quick look at one other useful Small Basic concept. In the
text window above, it would be nice if there was a blank line between each input
request. This just makes your output appear a little cleaner, a quality of a well
designed Small Basic program. To insert a blank line in the output, just use a
WriteLine method with a blank argument:
TextWindow.WriteLine("")
Add the shaded line to the current code:
TextWindow.Write("Whatisyourage?")
UserAge=TextWindow.ReadNumber()
TextWindow.WriteLine("Youinput"+UserAge)
TextWindow.WriteLine("")
TextWindow.Write("Whatisyourname?")
UserName=TextWindow.Read()
TextWindow.WriteLine("Youinput"+UserName)
Run the program again and answer the prompts. Notice the new blank line.
This program has been saved in the InputExample folder in the course programs
folder (\BeginSB\BSB Code).
4-14
4-15
Program Development
Start Small Basic. Click the New Program button in the toolbar. A blank
editor will appear. Immediately save the program as Savings in a folder of your
choice.
First, type the following header information and code that adds a window
title:
'
'SavingsProgram
'BeginningSmallBasic
'
TextWindow.Title="SavingsCalculator"
We will use four variables in this program: one for the users name (YourName),
one for the deposit amount (Deposit), one for the number of months (Months)
and one for the total amount (Total). Type these lines to initialize the variables:
YourName=""
Deposit=0.0
Months=0
Total=0.0
4-16
any time, after typing some code, you might like to stop and run just to see if
things are going okay. That is always a good approach to take. First, ask the user
his/her name using this code:
'askusername
TextWindow.Write("Hello,whatisyourname?")
YourName=TextWindow.Read()
Next, determine how much will be deposited in the savings account each month:
TextWindow.WriteLine("")
'getdepositamount
TextWindow.Write("Howmuchwillyoudepositeachmonth?")
Deposit=TextWindow.ReadNumber()
Notice the insertion of a blank line before printing the prompt. Finally, obtain the
number of months:
TextWindow.WriteLine("")
'getnumberofmonths
TextWindow.Write("Forhowmanymonths?")
Months=TextWindow.ReadNumber()
With this information, the total deposit can be computed and displayed using a
WriteLine method:
TextWindow.WriteLine("")
'computeanddisplaytotal
Total=Deposit*Months
TextWindow.WriteLine(yourName+",after"+months+"months,
youwillhave$"+total+"inyoursavings.")
TextWindow.WriteLine("")
Save your program by clicking the Save button.
4-17
The finished code in the Small Basic editor should appear as:
'
'SavingsProgram
'BeginningSmallBasic
'
TextWindow.Title="SavingsCalculator"
'initializevariables
YourName=""
Deposit=0.0
Months=0
Total=0.0
'askusername
TextWindow.Write("Hello,whatisyourname?")
YourName=TextWindow.Read()
TextWindow.WriteLine("")
'getdepositamount
TextWindow.Write("Howmuchwillyoudepositeachmonth?")
Deposit=TextWindow.ReadNumber()
TextWindow.WriteLine("")
'getnumberofmonths
TextWindow.Write("Forhowmanymonths?")
Months=TextWindow.ReadNumber()
TextWindow.WriteLine("")
'computeanddisplaytotal
Total=Deposit*Months
TextWindow.WriteLine(yourName+",after"+months+"months,
youwillhave$"+total+"inyoursavings.")
TextWindow.WriteLine("")
4-18
Run your program. If the program does not run successfully, try to find out
where your errors are using any error messages that may appear. We will cover
some possible errors in the next class.
When the program runs successfully, you will see:
Type in your name, a deposit amount and a number of months. Your total will be
given to you in a nicely formatted string output. Notice how the name, deposit,
months and total are all put together (concatenated) in a single sentence, along
with a dollar sign ($). Make sure the answer is correct. Remember, a big step in
program design is making sure your program works correctly! If you say you want
to save 200 dollars a month for 10 months and your computer program says you
will have a million dollars by that time, you should know something is wrong
somewhere!
4-19
Notice if I deposit 403.52 (you dont, and cant, enter the dollar sign) for 11
months, the program tells me I will have $4438.72 in my savings account.
This program may not seem all that complicated. And it isnt. After all, we
only multiplied two numbers together. But, the program demonstrates steps that
are used in every Small Basic program. Valuable experience has been gained in
recognizing how to read input values, do the math to obtain desired results, and
output those results to the user.
4-20
Most savings accounts yield interest, that is the bank actually pays you for
letting them use your money. This savings account program has ignored interest.
But, it is fairly easy to make the needed modifications to account for interest - the
math is just a little more complicated. We will give you the steps, but not show you
how, to change your program. Give it a try if youd like:
Define a variable Interest to store the yearly savings interest rate. Interest
rates are floating decimal numbers.
Modify the code to use Interest in computing Total. The code for that
computation is (get ready - its messy looking):
Total=1200*(Deposit*(Math.Power((1+Interest/1200),
Months)1)/Interest)
Make sure you type this all on one line as often happens, the word
processor has made it look like it is on two. As we said, this is a pretty
messy expression, but its good practice in using parentheses and a
mathematical function (Power). The number 1200 is used here to convert
the interest from a yearly value to a monthly value.
Now, run the modified program. Type in values for deposit, months, and interest.
Make sure you get reasonable answers. (As a check, if you use a deposit value of
300, a months value of 14, and an interest value of 6.5, the total answer should be
$4351.13. Note youd have $4200 without interest, so this makes sense). Save
your program.
4-21
I told a little lie, I didnt get $4351.13 in the above example with interest. I
actually got $4351.1272052172923076923076923!!!:
I rounded the answer. In such cases, the number should just be displayed with
two numbers after the decimal. It is possible to do this using Small Basic but
beyond the scope of our discussion at the moment.
4-22
Summary
Notice the programs are getting a little more detailed as you learn more
Small Basic. In this class, you learned about proper program design,
mathematical functions and how to add input capabilities to your Small Basic
programs. You built a little savings account program. And, an important concept
to remember as you continue through this course is to always try to build your
programs a few lines of code at a time. A good mantra is code a little, test a
little. You will introduce fewer errors in your programs using this approach.
from
Our BibleByte Books Publishing Division also offers several Beginning Computer
Programming Tutorials for Christian Schools and Homeschools. These tutorials
cover the same material that is found in our Beginning Programming Tutorials
except that we have added several Computer Bible Games for Christian School
Students to learn and develop.
Kidware Software also offers several Microsoft Small Basic Programming books
which help introduce the Microsoft Small Basic Development Environment to kids
and adults. These Small Basic Programming books are appropriate for Middle
School students and early High School students. Beginning Small Basic
programming adults will also find these fun and engaging as well.
David Ahl's "Small Basic" Computer Adventures
David Ahl's Small Basic Computer Adventures is a Microsoft Small Basic
re-make of the classic BASIC COMPUTER ADVENTURES programming
book originally written by David H. Ahl. This new book includes the following
classic adventure simulations; Marco Polo, Westward Ho!, The Longest
Automobile Race, The Orient Express, Amelia Earhart: Around the World
Flight, Tour de France, Subway Scavenger, Hong Kong Hustle, and Voyage
to Neptune. Learn how to program these classic computer simulations in
Microsoft Small Basic. This "intermediate" level self-paced tutorial can be
used at home or school.