Phantasmal MUD Lib for DGD

Phantasmal Site > DGD > DGD Reference Manual (legacy) > Looping and Iteration

3.3 Looping and Iteration

The LPC language is well-suited to math-intensive tasks, as you'd guess from the previous section. For instance, let's say you wanted to find out how many times you'd have to double the number two before you got to some very high number. That's something you could probably do in your head or on paper for small numbers. But for a number like ten million, you're probably better off letting the computer do it.

Try typing code int times; int count; times = 0; count = 2; while(count < 10000000) { count = count * 2; times = times + 1; } return times; Note that you must not hit return until the very end — you have to type the whole thing on one line. If you do it right, you should get 23 as the answer.

But is 23 the right answer? Hard to tell. So we should start with 2 and double it 23 times, just to be sure. Go ahead and type code int times; int count; times = 0; count = 2; while(times < 20) { count = count * 2; times = times + 1; } return count;. You should get the value 16777216 returned. And yes, that's more than ten million. So our code works! Now, how does it work?

You know about declaring variables and setting values, but while is a new one. While takes a condition in parentheses, and then a bunch of stuff between curly braces. The stuff in curly braces is done over and over again until the condition in parentheses is false. So in the first example above, the code will keep doubling the count variable and adding one to the times variable until count is no longer less than ten million. Then it will return count, which is how many times it had to double.

Once you understand the first example, you should be able to figure out the second example on your own.

There's another kind of loop called a for loop, which is very similar. The first example, written as a for loop, looks like this: code int times; int count; for(times = 0, count = 2; count < 10000000; count = count * 2, times = times + 1) { } return times; A for loop is a lot like a while loop, but the syntax is funny. Note that after the word "for", you have three different pieces of code in the parentheses, each separated by a semicolon. The first piece of the code is done before the loop begins. In this case, it sets times to 0 and count to 2. The second piece of code, count < 10000000 is checked every time through the loop. In this case it's checking whether count is more than ten million, just like the while loop did.

And the last section is done at the end of every time through the loop. So the things that were inside the while loop have moved to the for loop's third section of code. Putting code in the third section of the parentheses has the same effect as putting it in the loop body, so you can divide the code between the two however you like.

<— Prev
Variables and Arithmetic Expressions
Up
A Quick LPC Tutorial
Next —>
Simple String Manipulation