Variables & Constants

Programs often need to store pieces of data like scores for a game, or names of players. They store data like this in their thinking memory (RAM). To do this the program has to create a space in the memory to put that piece of data.

Variables

A variable is a memory location used to store data. The value can be changed when the program is running.

Constants

A Constant is a memory location used to store data. The value does not change when the program is running.

Atomic Data Types

The RAM is like a set of shelves. When you create the space to store some data, you give the shelf a label (a name) and you say what type of data will go on the shelf (Numbers, Strings, Characters or Boolean).

Some programming languages do not require you to say it's data type, but you always need to know that it does store the data in different ways.

Identifiers

We must give variables sensible names so that we can use them within our code. There are some rules you must follow when choosing variable names.

  • variable names cannot start with a number e.g. 1stCalculation
  • variable names cannot have spaces e.g. my variable
  • variable names cannot be reserved words e.g. print

When you want to use two words in your variable name we can use camel case (a capital letter for each word) to show the break between words. For example if you wanted to create a variable called total numbers, you could call your variable totalNumbers. Other examples may be myFirstNumber, totalNumberStudents

Identifier

The name given to a variable or constant to that is can be ‘identified’ and used in a program.

Declaring and Assigning Values

Variables (and constants) need to be allocated a space in memory. This is called declaring.

In many languages you must also declare the type of data that will be stored in the variable.

In Pseudocode we assign a value to a variable using the arrow.

name ⇽ "Bob Smith"

In Pseudocode we only need to declare constants (and assign a value at the same time).

Constant passmark ⇽ 45

It is useful when writing in Pseudocode to indicate the datatype of variables/constants the first time they are used, so that if a programmer is using your plan to create a program in a static programming language they will know that datatype to use when declaring the variables. So the above examples would be written as follows...

name ⇽ "Bob Smith"       //STRING
Constant passmark ⇽ 45   //INTEGER