Ok, so we’ve got a simple program. It prints “Hello” all over the screen but I could do that on a piece of A4 with a biro. How do we actually make the computer do anything useful.
A variable sounds very complicated doesn’t it. Well, it’s actually quite simple. It’s a bit like the memory on your pocket calculator but rather than just having one, you can have as many as you like.
Variables are assigned with the command LET. So, if I wanted to set the variable A to be the value 123, I would write a program like this:
10 LET A = 123
OK. Not a very interesting program. I’ll grant you that. We can however do some interesting things with variables. Let me expand the program a bit more:
10 LET A = 123 20 PRINT "The value of A is "; A 30 LET A = A + 1 40 PRINT "The value of A is now "; A
The output of this program is:
The value of A is 123 The value of A is now 124
It should be fairly easy to follow this program.
- Line 10: The variable A is set to the value 123
- Line 20: Prints the text “The value of A is” followed by the value of the variable.
- Line 30: This is quite clever. It reassigns the variable A to the value of A+1, so A is now 124
- Line 40: Prints out the new value of A
Now this is where the calculator memory analogy falls down. Computers can also store text in variables. Variables of this type are called String Variables and in BASIC have a “$” symbol after the variable name.
For example, we could add this line to our program:
15 LET A$ = "The value of A is "
Note that strings are always enclosed within quotes.
We can now write our program to use this new variable like this:
10 LET A = 123 15 LET A$ = "The value of A is " 20 PRINT A$; A 30 LET A = A + 1 40 PRINT A$; "now "; A
The output of this program is identical to the previous program, but with one advantage. In the first program if we needed to alter the text printed, we would have to change two lines of code. In the new program, we just change the text in the string definition on line 15.
This may not be a biggie with this program but if the program contained thousands of lines of code and you did not know where the text was, it could save you hours.
Next, we’ll learn how computers make decisions…