Variable
A variable exists to store a value in a location (in memory) identified by a symbol (a name). When creating a variable we identify what kind of datatype it is (integer, real (float), boolean, character, string). We assign it a name which should ideally provide some indication of what kind of information we are storing in it. For example, if we are storing customers first names we might name the variable custFirstName. There should never be any spaces in a variable name. The convention of using uppercase letters to indicate the start of each word is known as camel case.
When creating a variable we should enter a blank or default value – this is known as initialisation. There is an important reason to do this. When a variable is created it identifies a memory location where the data will be stored. If we do not enter a value at that time whatever was in that memory space previously can become the value in our variable, this can lead to errors in the program. It should be noted, not all programming languages do this. When creating a string, if you do not want anything in there you would do something like this:
firstName ← ""
this would create a string variable called firstName containing null. Null is not zero or space, it is an empty value.
Constant
If you create this kind of variable
THISISPI ← 3.14
it means you cannot change the value of 3.14. This is so other programmers (and yourself) cannot change an important value that should never be changed throughout a program. In pseudocode, it is common to UPPERCASE the variable name to indicate it is a constant.
Arrays
Arrays are variables that are complex datatypes. When creating arrays we use the [ ] square brackets to indicate the fact it is an array, to set how many indices the array has, and to identify which indice we are storing or getting the data. For example:
scores[5]
Would create an array with 5 indices (5 locations to store, in this case, integers).
| 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|
scores[0] ← 4 scores[1] ← 99
This would store the value 4 in the first indice (location) and 99 in the second indice of the scores array. Bear in mind sometimes the WACE exam questions will start an array at 1 – programming languages start at 0 to avoid wasting memory.
| 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|
| 4 | 99 |