Sometimes we need computers to remember the information we give it and that it calculates during programs. A variable can be thought of as a box that the computer can use to store a value. The value held in that box can change or ‘vary’. A program can use as many variables as it needs it to.
All variables are made up of three parts:
- a name
- a type
- a value
Why use variables?
Variables are extremely useful when programming. If a variable is used for the length of a side in a simple program to calculate the perimeter of a square, it is easy to calculate the perimeter of a different sized square, simply by changing the value of the variable.
Variables are a key element of programming. They are used for calculations, for storing values for later use, in decisions and in iteration.
Iteration
An algorithm is a plan, a set of step-by-step instructions designed to solve a problem. There are three basic building blocks (constructs) to use when designing algorithms:
- sequencing
- selection
- iteration
Algorithms are used to help design programs that perform particular tasks.
What is iteration?
Algorithms consist of steps that are carried out one after another. Sometimes an algorithm needs to repeat certain steps until told to stop or until a particular condition has been met.
Iteration is the process of repeating steps.
For example, a very simple algorithm for eating breakfast cereal might consist of these steps:
- put cereal in bowl
- add milk to cereal
- spoon cereal and milk into mouth
- repeat step 3 until all cereal and milk is eatenù
- rinse bowl and spoon
The algorithm will repeat steps 3 and 4 until all the cereal and milk has been eaten.
Why is interation important?
Iteration allows us to simplify our algorithm by stating that we will repeat certain steps until told otherwise.
This makes designing algorithms quicker and simpler because they don’t have to include lots of unnecessary steps.
Iteration in programming
Once an algorithm has been designed and perfected, it must be translated – or programmed – into code that a computer can read.
We create programs to implement algorithms. Algorithms consist of steps. Programs consist of statements. A statement is a single instruction - in other words, a single step.
Iteration is implemented in programming using FOR and WHILE statements.
In programming, iteration is often referred to as ‘looping’, because when a program iterates it ‘loops’ to an earlier step.