I'm looking for a set of concrete examples that illustrates good use cases of using a
for vs a
while loop for beginners. I feel that I have a good grasp on teaching them about these loops in the abstract (e.g., definite vs indefinite loops, how we apply those concepts in life), but I would also like to show two (hopefully somewhat contextually related) motivating programming examples - one where a
for loop is more appropriate, and one where a
while loop is. Obviously either type of loop can be used in either instance, but I would like to prompt students to think more about when to use one versus the other. Coming up with two good examples that are illustrative of this point is eluding me.
To further limit the options available, students only know about console I/O,
double types/variables, conditionals, and
while loops. We are using Java.
So, for example, if I wasn't so focused on finding something that beginners could implement, I would show that a good use of a
while loop is for a robot that should always be listening for voice input from a user; this is a good use, because we don't know when (i.e., after how many iterations) we will stop listening for voice input. I would then contrast this with a robot parsing through transcriptions of user voice input to identify keywords and respond to them. I've considered trying to translate this into console I/O, but the use of looping to continuously look for console input lends itself somewhat better to
do-while loops, which we'll cover next.
I realize my question is likely a rehash of what was asked here, but I wasn't happy with the answers. Answers on that post dealt more about the ordering of topics for teaching loops (e.g.,
while loops before
for loops), or real-world motivating examples (e.g., while I'm not full, continue eating pizza). What I'm looking for is more in line with the later, but I would like to do something that translates well into code.