# Example for For vs While Loop (in Java)

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.

• This question is specifically for motivating examples? – Ben I. Oct 2 '17 at 2:44
• @BenI. Yes, I am looking specifically for examples that I could show in code. – cryptic_star Oct 2 '17 at 3:08
• I don't think your description of the difference between for and while 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). – wvxvw Oct 2 '17 at 6:25
• What language? (python for in much like C# foreach) – ctrl-alt-delor Oct 2 '17 at 8:35
• The for loop (in C-ish languages) is here to give a clear separation between the control and the code to be executed at each turn. Then it leads to idiomatic forms, like the well-known for(int i=0; i<n; i++), or for(char *p = str; *p; p++) that every programmer recognizes without thinking. Can be done with while, but the i++ part would be hidden far away. So the preference of the students for for over while 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". – Michel Billaud Oct 2 '17 at 8:38

If I'm interpreting your question correctly you'd like real life examples that translate to code. Maybe something like the following.

• You want to drive or ride your bike to the ice-cream shop a few miles away. You don't know how far it is exactly but you will recognize it when you get there (while), VS You want to ride your bike 15 miles out and then return and you have an odometer on the bike (for)

• You want to shoot baskets until you have made 100 attempts (for) VS You want to shoot baskets until you have made 50 successful shots (while). Outside the US, substitute free kicks.

• You want to write a 15 page paper on looping in Java (for) VS You want to work on your "looping in Java" paper until you are satisfied with the result (while).

• You want to boil potatoes until a fork can be easily inserted (while) VS You want to boil potatoes for 11 minutes (for).

To translate these into code you need some imagined functions for the actual activities (void boilPotatoes()).

For some of them it is useful to discuss the empty case: you are already at the ice-cream shop, etc. For others, a discussion of "at least one iteration" might be useful to have.

If you want to include foreach in the game:

• You want to polish all of your mom's teacups (foreach) VS You want to polish her ten most valuable teacups (for) VS You want to polish teacups until you run out of polish (while).
• These don't look like console based tasks, they are 'human robot' tasks... – Sean Houlihane Oct 2 '17 at 12:04
• I'd interpret it differently: find good examples of for/while in concrete java applications, not "real life examples" which are not related to programming. – Michel Billaud Oct 3 '17 at 9:22

You would know beforehand when the for loop would terminate, this is not clear in a while loop. I basically tell my students "if you know when it ends, it's a for". (Sure, one can construct pathological cases and there is always this for (;;), but for basic understanding this issue is the crucial difference between for and while.)

As for examples:

• print all elements of this array is a for,
• play so many rounds of tic-tac-toe until the human player quits: while.

You might want to force them to convert for to while in an exercise and demostrate that the converse is not always possible.

• Yes, I think these are generally good examples, but don't fit in the constraints laid out in the original question (e.g., my students don't yet know data structures). – cryptic_star Oct 4 '17 at 2:56
• Count numbers from 1 to 10? Next lession: if, break, continue and count only odd numbers and stop when encounter a cubic number? It feels hard to describe exactly the difference between for and while if there are no things that have no a priori known size. But user input, as hinted below, might be a good idea. – Oleg Lobachev Oct 4 '17 at 23:07
• Yes, we actually did many of those exercises earlier. I provided an answer to this question that I think did a decent job demonstrating the principle. – cryptic_star Oct 5 '17 at 1:28
• As you say, if there is a list or known (or determinable) number of things, use for or foreach (or equivalent) - loop through an array, iterate through POST values, etc. If the required number of cycles is unknown (reading from a file, letting a user guess something, etc) then it is a while or until (or equivalents) – ivanivan May 9 '18 at 12:55

Having looked through all the answers thus far the other day, I'm not entirely satisfied with any of them (I'll try to take the time later and go through to leave comments). However, for now, I'll post what I came up with for class.

First, I want to emphasize that these students only know what was mentioned above, no arrays/data structures, very little in terms of methods (just some of the ones for String), and little beyond the foundations of OOP (e.g., can't yet actually implement a class). Additionally, we have no hardware (or at least, not enough of it).

I went with a general goal of String processing, since they have done a fair amount of that. For illustrative purposes, we just printed items out to keep it simple, but discussed modifications for finding/replacing characters/patterns, other things you could do with this (we'll extend these tomorrow for nested loops). Note that they don't know toCharArray() and split() since we haven't yet discussed arrays, but the below examples replicate much of that functionality.

For a for loop, print each character of a String to its own line.

String sentence = "Some example sentence";

for (int index = 0; index < sentence.length(); ++index) {
System.out.println(sentence.charAt(index));
}


For a while loop, print each word of a String to its own line.

String sentence = "Some example sentence";

while(sentence.indexOf(' ') >= 0) {
System.out.println(sentence.substring(0, sentence.indexOf(' ')));

sentence = sentence.substring(sentence.indexOf(' ') + 1, sentence.length());
}

System.out.println(sentence);


Yes, there are better ways of writing the above, but I wanted to start by emphasizing the use of the while loop, and then modifying it to handle that last word.

In general, this prompted a nice discussion of definite vs indefinite loops, and particularly the various shades of indefinite. One student pointed out that we could use replaceAll() to figure out the number of spaces in a String (i.e., replace all the spaces with nothing, compare lengths), but others thought that too much work to bother with before writing the loop.

Anyway, I would appreciate critiques of this for next time I teach CS1.

• Something your answer alludes to that I'd not seen in the others, an imprecise example can be good if it results in a discussion. – Sean Houlihane Oct 4 '17 at 13:22
• @SeanHoulihane Could you clarify? I'm not sure I see what you mean. – cryptic_star Oct 4 '17 at 15:42
• You say 'there are better ways of writing the above' ... 'this prompted a nice discussion'. So you may not have meant that the discussion was about better ways of doing it, but if you're presenting some code to introduce a topic (rather than presenting a problem to be solved by the students, as I inferred in the Q), showing an example which can be improved upon is often constructive. – Sean Houlihane Oct 4 '17 at 15:47
• @SeanHoulihane Yes, I concur! – cryptic_star Oct 4 '17 at 15:55

Robots are certainly a good idea, but it sounds like you don't have any suitable hardware - I think simple hardware will give you plenty of opportunities and may also provide a different 'hook' for some of your students to become interested.

As an abstract level, while is a good fit for a background task as you identified. If you're using a console interface, you need to make up something along the lines of a screen saver (assuming there is no actual processing). Maybe the program can prompt for input, generate bad poetry, or draw some simple snake like animations. All the time, waiting for 'control' input. Alternatively, some experimental data collection if you have suitable I/O hardware.

Once you have the control, you want to demonstrate iteration with for. If you were using a micro:bit you could loop through a text string to display the result of some measurements. All you need is a set of data-points collected during the 'while' period. This could be a mash-up of the inputs generated by the user.

So, as a scenario:

while (user has not said 'stop')
Collect user inputs
Generate random vogon poetry for the user
foreach(user input before stop)
Congratulate user on writing the following work of art
Repeat input with words mangled or re-ordered


typical for loop: loop over an interval. You can easily separate the control part (the successive values of the loop variable) and the calculations.

for (float eur = 1; eur <= 10; eur += 0.5) {
float usd = eur * 1.17345;
println(eur,"EUR is ", usd, " USD today");  // Processing
}


typical while loop

float x = 2;
float epsilon = 0.001;

float a = x/2;   // approximation of square root

while(abs(a * a - x) > epsilon) {
a = (x/a + a) / 2;
}
println ("square root of", x, "is near", a);


Two examples based on a common theme (financial calculations)

• print the table of composed interests over 10 years (loop with counter)
• how many years does it take to double your capital at some interest rate (while not enough, etc)
• The first example is counterproductive. Students should be taught not to use floating point for types such as "money" which are inherently fixed-point decimal values. – Peter Taylor Oct 2 '17 at 14:09
• @PeterTaylor I agree you should teach them to use java.math.BigDecimal for real money calculations. The use of such objects in the for loop is left as a funny exercise to the reader. – Michel Billaud Oct 2 '17 at 16:56
• Actually, the first example is worse than that. Using floats in any counting situation can easily lead to a classic "off by one" error". You have to assume that 0.5 is exact (which it likely is) but other very similar situations will fail. Try to count by 0.2 for example, up to about 1000.0. (I don't know if that one actually fails, but some will). Just as in base 10, 1/3 isn't precisely representable, many things in base 2 are not. – Buffy Oct 3 '17 at 10:47
• And note that BigDecimal is arbitrary precision. But that isn't the same as infinite precision. Rounding happens. Good enough for money, but not for everything. – Buffy Oct 3 '17 at 11:24
• @buffy Of course it happens, and it has to, for money handling applications. The way it happens (precision, rounding mode) is defined by the MathContext docs.oracle.com/javase/8/docs/api/java/math/MathContext.html BTW who assumes the loop had to stop exactly on value 10 ? – Michel Billaud Oct 3 '17 at 11:37

When looping through a collection, a for loop is best. The collections for loops in Java, JavaScript and Python prevent you from accessing indices that are out of bounds. Most of the time, they are the right choice for traversing a collection. The for loop is mostly a "definite loop."

The while loop is at its most useful when some indefinite number of iterations is required to perform a task. For example, you might be asking a user for a specific type of output. IF the user fails to enter something valid, you nag that user with prompts until he does the right thing.

• Your while loop example is my do while example - always prompt the user once for input, and if they enter something invalid, continue to ask. And while your first example is good, as the question notes, these are very early programmers I'm teachings, without any sort of data structure beyond a variable yet. – cryptic_star Oct 10 '17 at 4:16

So we know that we can use for and while, for all loops, but here are some simple rule as to when to use which one, to make programs easier to read, and understand.

If you can, use foreach: If iterating over a list (or other iterable type). Note python calls foreach for. foreach can not always be used, but is much safer and easier to use, when iterating over things.

For experts, if you don't have foreach, then use for for bounded loops, that is those that could be implemented with a foreach, those that you know how many times you will loop (or the upper bound, in the case when you will break out early).

e.g.

foreach item in list {
process item
}

for (TypeOfItem item : list) {
process item
}


However for beginners for loops, can be very confusing (I am not discussing foreach, or for in python). Therefore prefer while loops over for loops. But foreach loops over while.

See image from LearnableProgramming — Bret Victor, showing program flow through a for loop.

In C like languages (C, C++, Java, C#, …), always use for in the form for(int i=0; i<n; i++) (there may be some exceptions, but rare). So you are using for to construct a foreach, as the language does not have the higher level structure. (C# has foreach; C++ has library implementations; Java has foreach, but uses keyword for)

• This is not an example of engaging exercises, it is a tutorial on the syntax. – Sean Houlihane Oct 2 '17 at 9:14
• @SeanHoulihane “I'm looking for a set of concrete examples that illustrates good use cases of using a for vs a while loop” — so while not example, it is a rule, that can be taught and used to generate examples. – ctrl-alt-delor Oct 2 '17 at 12:09
• but we all know the rules, and if we wanted to learn about the rules, we'd be on SO... – Sean Houlihane Oct 2 '17 at 12:10
• Since reading an article (now cited in my answer), I have changed my mind about the wisdom of teaching for loops to beginners. – ctrl-alt-delor Nov 3 '17 at 17:55