| Examples
:
repeat example
To find the maximum number of a
sequence of numbers ending with -1
| program maximum(input,output): |
| const |
| sentinel = -1; |
| var |
| max,num : integer; |
| begin |
| max: = -maxint; |
| writeln('Enter the values'); |
| repeat |
| read(num); |
| if num > max then max:=num |
| until num=sentinel; |
| writeln(max); |
| end. |
for example
Write a sequence of numbers beginning
with 0 and ending with 20 including only the even numbers
| program even(input,output); |
| var i:integer; |
| begin |
| for i:=0 to 10 do |
| writeln(i*2); |
| end. |
while example
Same problem as for repeat-until
example.
| ......... |
| begin |
| max:= -maxint; |
| writeln('Enter the sequence'); |
| read(num): |
| while num<>sentinel do |
| begin |
| if num > max then max:=num; |
| read(num); |
| end; |
| ........... |
The following applet is here to illustrate you the basic differences
between the 3 loop statements. With this you can, e.g , see the difference
of execution begin and stop between while and repeat-until.
In the first box, you can enter a for loop code pice and when you click
onto the 'Start For' button, you see the output in the 4. box. The same
applies for the while-loop and the 2.box and the repeat-until loop and
the 3.box.
There are several restrictions for using this applet.
-
It does not handle all possible loop-codes but only specific ones. As this
applet is only made to illustrate you the difference between the loop-statements,
it only accepts write and writeln's as statement within begin..ends of
the statements.
-
The for-loop should not have any begin..ends in its box. It should only
have the loop-statement and a write or writeln-part.
-
The while loop should be preceded with the initialization of the loop variable.
Then comes the while-statement and a begin with a following write or writeln
statement, and expression changing the loop-variable and an end.
-
The same restrictions as while.
Examples for use with the applet:
For the for-loop:
| for i:=1 to 6 do |
| writeln('abcde'); |
For the while-loop:
| i:=10; |
| while i>2 do |
| begin |
| writeln('abcde'); |
| i := i-3 |
| end; |
For the repeat-until loop:
| i:=1; |
| repeat |
| writeln('nilay'); |
| i:=i+2 {no semicoln here, do not forget!} |
| until i=13; |
|