Sign in Join
Wiki copytemporary

Basic Pascal Tutorial/Chapter 3/FOR..DO

Sent here from FOR..DO.

English · Français · Български · 中文(中国) · 日本語

FOR...DO Loops (author: Tao Yue, state: changed)

FOR...DO is a loop construct in Pascal. Of course, that may raise the question "What is a loop?".

Loops

Looping means repeating a statement or compound statement over and over until some condition is met.

There are three types of loops:

FOR...DO Loop

In Pascal, the fixed repetition loop is the for loop. The general form is:

pascal
for index := StartingLow to EndingHigh do
  statement;

The index variable must be of an ordinal data. The index can be used in calculations within the body of the loop, but its value cannot be changed (i.e. count:=5 will cause a program exception.)

In Pascal, the for loop can only count in increments (steps) of 1. A loop can be interrupted using the break statement. An example of using the index is:

pascal
sum := 0;
for count := 1 to 100 do
begin
  sum := sum + count;
  if sum = 38 then break;
end;

The computer would do the sum the long way and still finish it in far less time than it took the mathematician Gauss to do the sum the short way (1+100 = 101. 2+99 = 101. See a pattern? There are 100 numbers, so the pattern repeats 50 times. 101*50 = 5050. This isn't advanced mathematics, its attribution to Gauss is probably apocryphal.).

In the for-to-do loop, the starting value MUST be lower than the ending value, or the loop will never execute! If you want to count down, you should use the for-downto-do loop:

pascal
for index := StartingHigh downto EndingLow do
  statement;

See also

While ...Do loops

Repeat... Until loops

For... in loops


From the Free Pascal wiki, page "Basic Pascal Tutorial/Chapter 3/FOR..DO", as it stood on 2022-08-20 after a change by Kai Burghardt, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's Licensing page. If you have concerns about this material, message the admin.

Revision 1, last changed by WikiArchive .

Talk about this page

Nobody has opened a bench for this page yet. Sign in to open one.