3. Your First Small Basic Program

- Chapter 1: Introducing Small Basic
- Chapter 2 : Small Basic Program Basics
- Chapter 3 : Your First Small Basic Program
- Chapter 4 : Small Basic Program Design, Input Methods
| ## 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 | This chapter is adapted from the book 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 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 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 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 LessonAt 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. ## VariablesAll 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 ## Variable NamesYou must - 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:
As mentioned in an earlier class, the Small Basic language is not case sensitive. This means the names ## Variable TypesWe need to know the The first variable type is the
What if the variable you want to use will have decimal points. In this course, such variables will be of
The next variable type is a
One last variable type is the 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 StatementThe simplest, and most widely used, statement in Small Basic is the VariableName = VariableValue Note that only a single variable can be on the left side of the assignment operator (
The actual values assigned to variables here are called 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 ( ## Arithmetic OperatorsOne 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
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 - 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 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:
Notice a couple of things here. First, notice the parentheses in the ## String ConcatenationWe 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 NewString = "Beginning Small Basic " + "is Fun!" After this statement, the string variable 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. ## CommentsYou 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 To place a comment in your code, use the comment symbol, a single apostrophe (
Or, you can place the comment on the same line as the assignment statement: NumberBananas = 14 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 OutputYou’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 TextWindow.WriteLine(StringValue) In this expression, TextWindow.WriteLine("Welcome to Beginning Small Basic!") And saw that What if you want to output numeric information? It’s really quite easy. The
If you run this code, a I started a new program in Small Basic and typed these lines in the editor: When I run this code, I see (I resized the window): You can also combine text information with numeric information using the concatenation operator. For example, this code:
will print The numeric 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:
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 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:
In this case, the two numeric values are summed before being converted to a string and you will obtain the desired output of So, we see the 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 PartyYour 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 ## Program DesignAssume 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 DevelopmentStart First, type the following header information as a multi-line comment and add a title to the text window:
We will use five variables in this program: one for how much each person can eat (
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:
We have used something not seen yet – the Also, notice when you start type the line computing Eaters1, the intellisense drop-down now includes added variables like Display the results using the
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:
Double-check to make sure each line is typed properly. ## Run the ProgramSave your program (click the 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 TryFor 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 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
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 ## SummaryAgain, 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. © Copyright 2010 By BibleByte Books. All Rights Reserved. BibleByte Books, the BibleByte Books Logo, Computer Science For Kids, the Computer Science For Kids logo, and related trade dress are trademarks or registered trademarks of BibleByte Books. |