Loops. What are they and what are they for ?
A loop is a sentence that executes many times the instructions that are inside of it. Loops have a logical expression to indicate when it must stop, we write that stop condition. Each time the instructions are executed or a loop get completed, we say that it has been an iteration. A loop iterates while its logical expression returns true.
The first loop we’re going to see is
while, its behavior is very simple, it can be resumed in two steps:
- Evaluate the condition.
- If true, execute the instructions inside of it. If false do nothing.
Let’s see an example, imagine that Bart Simpson has to write the entire blackboard (100 times) with the phrase I will not instigate revolution, but he knows how to code in
c, so he writes in the blackboard a
while loop that looks like this:
If the blackboard could compile
c, the output would look like this:
I will not instigate revolution I will not instigate revolution I will not instigate revolution ... ... ... I will not instigate revolution I will not instigate revolution I will not instigate revolution
See the power of a loop, it turns a repetitive and tedious task into an easy one. The while has many other applications, our calculator program that just make a division has one, with the
while we could ask for the second number (denominator) while the user introduces 0, with the
while we validate our program and make it more comfortable to use because the program just not exit if the user introduces a 0, it keeps asking for a valid number. Let’s see how to do this:
The output could look like this, if we introduce
8 as the 1st number and 0 twice for the second one and finally a 2:
Introduce the numerator: 8 Introduce the denominator: 0 The denominator could not be 0. Please enter it again: 0 The denominator could not be 0. Please enter it again: 2 -------------------------- The division result is 4.000000
As you can see the
while loop will keep asking the second number while it is
0 and it will stop when the condition is false, that means when the second number is not 0, when that happens the program will continue…