Introduction

Basics of Programming

Variables

Input and Output

Boolean Expressions and Branching

Loops

Functions and Procedures

Files

Arrays

HOME

# Chapter 6

## Loops

One of the main advantages of using computers is that they can repeat a task thousands or even millions of times without getting tired. In programming, loops are used for repetitive tasks. Pascal has three types of loops: FOR, WHILE-DO, and REPEAT-UNTIL.

### The FOR loop

The simplest type of loop is the FOR loop. It loops for a specified number of times then stops. The format for the FOR loop is:

```FOR  counter := first  TO  last  DO  BEGIN

statements to be repeated

END;```

The counter can be any variable of type integer. It holds the iteration count for the loop.

After the counter is the number the loop starts at. It should always be an integer.

After the "TO" keyword is the last number the loop counts.

The last number should be followed by the keywords "DO" and "BEGIN" This marks the start of the loop's body. The program loops through the loop body for the specified number of times. The body is marked by the END statement.

```Program  Loop_Intro (input, output);

Var
i : integer;

{This program uses a loop to count from}
{ 1 to 100}

Begin

FOR i := 1 to 100 DO BEGIN
Writeln('The loop count is: ', i);
End;

END.```

### The WHILE-DO Loop

Unlike the FOR loop, the WHILE-DO loop uses a boolean expression to determine how many times it will execute. The format for the WHILE-DO loop is:

```  WHILE  boolean expression  DO  BEGIN

one or more Pascal statements

END;```

The loop keeps executing as long as the boolean expression is true. If the boolean expression is FALSE in the beginning the loop never executes. If the boolean expression becomes FALSE the loop stops executing. If the expression never becomes FALSE it will execute infinitely. This is called an INFINITE LOOP.

```Program While_loop_intro (input, output);

Var
x : integer;

Begin

x := 1;

WHILE x < 10  DO  BEGIN

Writeln('This is iteration # ', x);
x := x + 1;            {increment x}

End;

End.```

### The REPEAT-UNTIL Loop

The REPEAT-UNTIL loop is very similar to the WHILE-DO loop. One difference between the two is that the REPEAT-UNTIL loop puts the boolean expression at the end of the loop. That means that the body of the loop will be executed at least once before it tests the boolean expression. Another difference is that the REPEAT-UNTIL loop will execute as long as the boolean expression is FALSE.

```Program Repeat_Until_Intro (Input, Output);

Var
x : integer;

Begin

x := 1;

Repeat

Writeln('Iteration  #', x);
x := x + 1;

Until x > 10;

End.```