A Beginner's Guide to D/Conditions and Loops/Simple Looping

One of the simplest kinds of loops in D is the while loop. This loop will keep looping as long as its condition is true. This also makes the while loop very flexible—virtually any kind of loop can be written as a while loop, if you try hard enough. A while loop looks like this:

The while loop will see if the condition is true, and if it is, it'll run the code inside it. It'll keep doing that until the condition is false.

As was shown in the last section, the foreach loop is useful for looping over the contents of some kind of container. But what about when you don't know how much data you have, such as when you're reading from a file? A while loop can help in this case.

So here we create an array of strings named names to hold a list of names we'll read in from a file. Then we create a <tt>File</tt> object. Remember in the Basic Input section, where we used <tt>din</tt> to read a line of text from the console? <tt>din</tt> is really a kind of <tt>File</tt> object, so we're doing the same thing here, except we're reading from a file on disk instead of from the user.

The important thing here is the <tt>while</tt> loop. Let's have a closer look at it:

The condition is <tt>input.eof == false</tt>. The <tt>.eof</tt> method of <tt>File</tt> means "end of file." So we're going to use this loop to read data while we're not at the end of the file. In other words, we're going to read all the data out of the file. The body of the loop does just that—it reads a line from the file, and appends it to the end of our list of names.

At the end of our program, we write out the list of names, using the familiar <tt>foreach</tt> loop.

A second, very similar kind of loop is the <tt>do-while</tt> loop. In a <tt>while</tt> loop, the condition comes at the beginning of the loop, but in a <tt>do-while</tt> loop, the condition comes at the end. The reason this is significant is that with a <tt>while</tt> loop, if the condition is false the very first time, the loop body will never be run, so <tt>while</tt> loops can run their bodies 0 or more times. But with a <tt>do-while</tt> loop, the body is run at least once before the condition is checked. <tt>do-while</tt> loops look like this:

One case where this kind of loop comes up a lot is when you're trying to get valid input from the user. Usually you ask the user to enter something in, then you check it to see if it's valid, and if it's not, you keep asking them until they give you something good. This is what a <tt>do-while</tt> loop is for: it'll run the input code at least once, and keep running it until the condition is met.

This code uses the <tt>valid</tt> variable to keep track of whether what the user entered was valid or not. It'll be set to <tt>true</tt> once they do. Until then, though, the <tt>do-while</tt> loop will keep looping, asking for user input.