At its simplest, a Loop in programming involves making a section repeat. It means that instead of going on a different path, like selection, you repeat the same path.
There are two basic types of loop - definite and indefinite:
For example, say that we want to find the squares of all the numbers between 5 and 10
We can use the function that we created for a sqare number repeatedly but with a different number.
We could do it long-hand like this:
console.log(calculateSquare(5))
console.log(calculateSquare(6))
console.log(calculateSquare(7))
console.log(calculateSquare(8))
console.log(calculateSquare(9))
console.log(calculateSquare(10)
That is not efficient and repeating lines of code always introduces the risk of human error and typos.
In programming, we could divert the route through the program using an definite loop and write the line of code just once.
Diagrams are good at showing Selection - this is a Flow Chart. It shows the order of processing for the algorithm with the added advantage of showing the route too
In this example, we want to output the squares of all numbers between 5 and 10. Notice that:
When writing code, we will often have an interim stage where we write the program using mainly English.
This method is called PSEUDOCODE and is independent of any actual programming language.
We could write this code one of TWO ways - using a definite loop or an indefinite loop:
Here we use a FOR loop.
This method has the instructions for the counter to change as part of the FOR instruction.
There is no TEST - it is definite.
Here we use a WHILE loop.
This method has the instructions for the counter to change as part of the Loop code.
There is a TEST BEFORE every repetition - it is indefinite.
Here is how the code for the program is written in JS.
The concept is still that there is a controlling MAIN routine which calls a SUBROUTINE
This uses built-in functions:
This uses brackets:
the logic is: IF (condition is TRUE) follow the first path ELSE follow the second path
Here is how the code for MAIN routine and SUBROUTINE are written in JS.
The concept is that there is a controlling MAIN routine which calls a SUBROUTINE
This video shows the order in which the program is executed.