Looping With a Known Loop Count
Just do something 5 times.
Loops With a Known Loop Count¶
-
A very common looping task in programming is to loop a predetermined amount of times.
-
We can code this with
while
loops orfor
loops. They are all equivalent in functionality. However, programmers tend to favor thefor
loop for this. -
Let's look at it with the
while
loop first then thefor
. -
Here's a small program that does something exactly 5 times.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
- And here it is with a
for
loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
They look very similar. The main difference is that the for
loop has one less line of code.¶
The while
loop does the same thing, only differently.¶
Example: Fahrenheit-Celsius Conversion¶
Demo
- Demo: Fahrenheit-Celsius Conversion
- unit04/demos/demo-fahrenheit-celsius.html
Not everything that can be counted counts, and not everything that counts can be counted. -Albert Einstein
Read more¶
Related Reading
Pages 57 - 67
Hands on Work¶
Labs
- Lab05: While Loop with known Count
- unit04/labs/lab-05-while-known-count.html
- Lab06: For Loop with known Count
- unit04/labs/lab-06-for-known-count.html
Exercises
- Lab05 exercise
- unit04/exercises/exercise-05.html
- Lab06 exercise
- unit04/exercises/exercise-06.html