Loops
Now I will introduce you the concept of loops. A loop can repeat code. There are several kind of loops but we will start with the simplest loop - The while
loop.
While Loops
The while loop is a head-controlled loop. That means that the body will only be executed if the condition is true, otherwise the body will be skipped.
Here is the syntactic structure:
Here is a simple example:
Do-While Loops
The do-while loop is a foot-controlled loop. The body will always be executed and stops if the condition is false.
The struture:
A simple example:
This sample expects an userinput and write it back only if the user types not exit
.
For-Loop
A for loop can be used to iterate over arrays/iterators. To repeat code for a given number of iterations you can use ranges.
The definition of a for-loop:
A simple example to repeat code:
You can also use ranges to reverse the direction of the loop:
Exercices
Write a program to calculate the factorial of a given number with a while loop.
Would it be possible to solve this problem with a for loop?
Last updated