Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Delphi Tutorial Part 3

Loops
It can be very tedious for someone to write out code that needs to be repeated on more than occasion. Likewise, it can be impossible to predict how many times we want some code to repeated. REPEAT, WHILE and FOR are statements that enable us to avoid these kind of situations, and without them, programming would be almost certainlly a very dull task.

The WHILE statement is the most conventional form of a loop. If you want to execute lines of code repeatedly, but you unsure if you want to execute them in the first place, this is the loop to choose. While a certain condition is true, the code is repeated.


a:=1;
while (abegin
writeln(a);
a:=a+1;
end;


You can see by this example, the integer(a) is continuously output on screen until it is equal to or less than 3. Therefore, the numbers 1, 2 and 3 should be written on each line. You can see that this can be particularly useful when you need to ensure some code is repeated a certain number of times. Although, the FOR loop can do the same job but do the counting for you.


for i:=1 to 3 do
writeln(i);


This loop assigns the value 1 to the variable to begin with, and then counts up to 3 as it outputs each number turn by turn. The next example shows how the same can be applied to character variables (assigned as char), and also how loops can count down as well as up.


for mycharacter:='D' downto 'A' do
writeln(mycharacter);


This loop should result in the characters D, C, B and A to be output on screen in this exact order.

The last type of loop (REPEAT) executes code on at least one occasion, and then a check is made with an ending conditional statement. In contrast, the conditional statement is marked using the word UNTIL, and if the condition is true then the loop is stopped.


a:=1;
repeat
writeln(a);
a:=a+1;
until (a>3)
end;


Like the other examples, the variable a is output to the console with each iteration of the loop. The variable is incremented by one with each iteration until the number is larger than 3. Therefore 1, 2, and 3 are all written out on different lines.

In the next section of this tutorial you will learn how to organise your programs by sectioning parts of code into procedures or functions.


This post first appeared on The Computer Monkey, please read the originial post: here

Share the post

Delphi Tutorial Part 3

×

Subscribe to The Computer Monkey

Get updates delivered right to your inbox!

Thank you for your subscription

×