Search:
All Any

Part of mariaus.info network Subscribe via RSS
Follow on twitter Request a tutorial
Visitor request: Drawing hair in Photoshop
Create a cool web 2.0 navigation bar
Visitor request: Creating photo collages in photoshop
Create an automated reusable software box model
Create a background for a space scene
Photography and art inspiration # 1
Photography and art inspiration # 2
Photography and art inspiration # 3
Photography and art inspiration # 4
Go to first pageAdd to favorites (this)Contact page ownerRequest a tutorialSubscribe to the Tip Kit news
Request a tutorial
Introduction to Delphi, Part 8 - While and For loops

This tutorial will teach you how to use FOR and WHILE loops in Delphi.
In a previous tutorial, i've explained the basic usage of the IF statement. Now we're going a little deeper to analyse further usage of the same conditions that we use in IF statements. In the first part of this tutorial, we'll be talking about already familiar conditions only in a different structure - the while loop. In a second part - we will talk about another type of loop - the for loop. So let's get started.

The last tutorial explained how to do some actions if a condition is met and do other actions if it is not met. We will be analysing a very similar structure now, the only difference is that this structure is not executed only one time. It is evaluated until the condition in it is met. That is exactly the reason why it is called a loop. In loops, the condition is evaluated and, if met, the code is executed and the execution is looped back to the condition to be evaluated again. The example below shows a simple loop in a procedure:
procedure TestLoop;
begin
  while true do begin
    // do some code here
  end;
end;
We can see a loop that has a condition true. What does this mean? It's simple - means the condition is always met. So what happens if it is always met? Basically, the loop never stops. This is an infinite loop. You should be very careful while using the while loop, for it can result in situations where the loop starts to run infinately. In this example, the code will never go further than the first end; statement, because the condition in a loop is always true. So let's see another example. In this case, something that actually makes sense :)
procedure TestLoop;
var _execute: boolean;
begin
  Randomize;
  _execute := true;
  while _execute = true do begin
    if Random(10) = 5 then
      _execute := false;
  end;
  ShowMessage('Loop has stopped');
end;
To understand this code, let's first take a look at the Randomize procedure and Random function. The second one returns a random number in a range from 0 to the number we specify as a parameter. Only if you tried to run ir a few times - you'd realise that this function always returns the same set of numbers. This is why we have to use the Randomize procedure once to make the numbers really random. Well, actually they're not totally random, but that's not our subject and we don't care why it is so :) Everything else in the code should already be understandable to you, my dear reader, because it was explained in previous tutorials.
When the procedure starts, it first randomizes the random number seed. Then it sets the _execute variable to true. We will be using this variable to check wheather to run our loop or not. The next thing is a loop itself. In each iteration, the value of _execute is checked and the loop is executed if this value is true. Since we've previously set it to true, the first iteration will meet the condition and the code inside the loop will be executed. Now the code of the loop tries to generate a random number between 0 and 10. If the function returns number 5 - _execute variable is set to false, if not - nothing changes. So let's imagine the function returns 9. Then the condition in the IF statement is not met and we skip the next line. Now the loop ends, so we need to go back to the while line and start all over again (that's what a loop is for - to run over and over again). We check the _execute variable and it is still ... true. So we run the code in the loop again. Now let's pretend the Random() function returns number 5. Condition in the IF statement is met and the next line is executed. So the _execute variable is set to true. Once again, we reach the end of the loop and have to start all over again. Only this time, the _execute is false and the loop condition is not met! So the code in the loop can't be run - it is skipped. That means we finally get to the ShowMessage procedure and display a message on the screen. If you have understood what you've just read - you've understood what a loop is - congratulations! Look at the next example and try to guess how many times you will see a message on the screen:
procedure TestLoop;
var i : integer;
begin
  i := 1;
  while i <= 5 do
    ShowMessage('Annoying? :)');
end;
If you've thought of a number 5 - you're wrong! Why? Because it is a mistake that even experienced programmers make from time to time - an infinite loop. Why infinite? Simple - do you see anywhere in the code that the value of changes to something else than 1? I sure don't. So if it is always 1 - then it is always lower or equal to 5 (the condition in the loop is met). Now you'd have to kill the program to stop it :)
procedure TestLoop;
var i : integer;
begin
  i := 1;
  while i <= 5 do begin
    ShowMessage('Annoying? :)');
    i := i + 1;
  end;
end;
Here's the same procedure, only fixed. This time, the value of is increased in every iteration and the loop will only display the message 5 times.

The while loop is used in situations when we have no idea how many times we need it to run. Meaning the times, when its iteration count does not depend on us (maybe it depends on some random factor, maybe on the user, running the application etc.). When we know exactly how many times we need to run a loop - we use the for loop. Here's how you define a loop like this:
// accending loop
for VARIABLE := No1 to No2 do
begin
  // code here
end;

// descending loop
for VARIABLE := No2 downto No1 do
begin
  // code here
end;
As in the IF and WHILE statements, the begin .. end; parts are optional if only one statement of code has to be executed in a loop. Instead of a VARIABLE, we need to have an actual integer variable, No1 is a smaller number and No2 is a bigger number. In the first loop the VARIABLE is increased in every iteration starting with No1 and increased by 1 until it reaches No2. In the second loop - you guessed - the VARIABLE is first assigned the value of No2 and then decreased by 1 until it reaches No1. Let's see an example to clarify things:
procedure TestLoop;
var i : integer;
begin
  for i := 1 to 5 do
    ShowMessage('Annoying? :)');
end;
Here is the same as we tried to do with the last while loop, only much more simple. In this case, we do not need to bother increasing the variable , because it is done automatically. But it is only increased by 1, so if you need to increase it by any other number - you either use a while loop or simply do something clever :) For example you want to do a loop from 2 to 10 with a step of 2. Ok, you can do that with while loop, but do you really need to be that problematic? Why not do a loop from 1 to 5 instead? It will run exactly the same 5 times as the original loop. And if you need to have the value of the the same as in the original loop, you can multiply it by 2 inside of the loop.
There's really nothing else to explain about the for loop, because it's as simple as that :) Hopefully now you know how to annoy a friend with a 100 messages and hope you'll try not to play with infinite loops too much. In case you still don't know how to show a 100 different messages - here's how:
procedure AnnoyFriend;
var i : integer;
begin
  for i := 1 to 100 do
    ShowMessage('This is a message, no. ' + IntToStr(i));
end;
There's only one thing to clarify here: if you want to use an integer variable in a string - you can't do that. You need to convert it to a string to be able to add it to another string. The IntToStr function takes an integer as a parameter and returns its string representation. So the above procedure will show a message a 100 times with the number of the iteration at the end.

So go ahead and play with loops and ifs for a while until the next tutorial comes out :)

Article written by: Marius S.
This article is an intellectual property of its respective author. All images, used here are property of tip-kit.com if not stated otherwise.
Share this article
Digg del.icio.us Facebook Furl Google Reddit Slashdot StumbleUpon Technorati
How easy was it to understand? Was it useful?










Leave a reply
Your name:

Message:

Confirmation code
Please enter the above code:
There are no comments yet. You can use the above form to leave a reply.
Copyright © 2009 Tip-Kit.Com | Valid XHTML 1.0 | Powered By Isis | RSS