Lecture 10: Loops I: For |
For loop |
For variable
:= start_value
To end_value Do
instruction; |
The instruction is repeated a number of times, determined
by
the control parameters start_value
and end_value.
Since the loop is for doing things in a countable way, the
control
parameters variable, start_value
and end_value all have to be of
any
integer type. Do not forget to declare the variable (see lecture
5) Example:
This program is doing the following
|
Just like with the if ... then ... else structure, we can
also group instructions together with begin and end
in
loops:
For i := 1 To 4 Do begin WriteLn('Ola'); WriteLn('Eu chamo-me Peter'); end; |
output
Ola Eu chamo-me Peter Ola Eu chamo-me Peter Ola Eu chamo-me Peter Ola Eu chamo-me Peter |
Good code:
|
Bad code:
|
program code
For i := 1 To 2 Do WriteLn(2*i-1, ' Ola'); |
output
1 Ola 3 Ola |
The start_value and end_value
can also be variables or expressions that return a value of integer
type
or variables of the same type, for example:
program
code
PROGRAM ForLoopExample; Var i: integer;
begin
|
output
5 Ola 6 Ola 7 Ola 8 Ola 9 Ola |
Nested loops
|
|
|
||||
|
|
This program is doing the following
|