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, String
/int
/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.
for
andwhile
actually describes what happens in any reasonably popular language. These are just some used-to-be macros that due to historical reasons made their way into some programming languages. But there isn't really anything that warrants this particular number of kinds of loop keywords (some languages have more, some have less). $\endgroup$for
in much like C#foreach
) $\endgroup$for(int i=0; i<n; i++)
, orfor(char *p = str; *p; p++)
that every programmer recognizes without thinking. Can be done withwhile
, but thei++
part would be hidden far away. So the preference of the students forfor
overwhile
relies on their ability to abstract the control part from the repeated part. Takes some time and exercises, with usual structures like "do sthg for x between min and max". $\endgroup$