Chapter 2: Using Variables
Computer programs normally use (or process) data in some way to produce results. This normally relies on an INPUT from the program or user, which is then PROCESSED by the program and finally displayed in some way in the console window, i.e. OUTPUT.
This shows the structure of a Small Basic program.
The input to the program is often supplied by the user whilst the program is running. In order to be able to do this the program must have some way of remembering the values that have been input, and you, the programmer, needs to know how to access them to make the program process what they contain. To do this we use a feature called VARIABLES.
The assignment statement
To store something in a variable you need to use an assignment statement. For example:
The example on the left stores the value 8 to the variable called NumberOne.
The ‘=’ is the assignment operator; the value on the right is what is stored in the variable that is identified on the left of the assignment operator. It can be read as “becomes equal to” or “takes the value”. Don’t think of it as ‘equals’ as this is not true until after the assignment has been made.
An assignment statement can also contain an expression (calculation) on the right side of the ‘=’, which will be evaluated when that statement is executed.
The above statements will result in the variable SUM ‘becoming equal to’ the value 23. Notice that I have added white space to the above assignments just to make it easier for me to read. Remember, Small Basic ignores the white space so, if it makes it easier for you, use it.
The TextWindow.WriteLine() Statement
If you want to display the contents of a variable, you need to use the TextWindow.WriteLine statement and provide the variable identifier in brackets:
Variables are NOT put inside quotation marks as this would make them into what is called a literal. Using TextWindow.WriteLine( “Sum” ) will output the word ‘Sum’ not what the variable Sum contains.
To output a sentence made up of variables and literals on one line of the Text Window you should use the output statement TextWindow.Write() to display each individual item as shown below. This displays its output without going on to the next line. The example on the left is shown in the image on the right below:
Notice that only the spaces inside the quotes are output to the screen.