Looping
There are times where you need to execute lines of code a couple of times, or iterate through the characters of a string, etc. So, what type of looping methods are available?FOR LOOP
A for loop is one of the fastest loops in Pascal. What makes it so fast? You are specifying a START and END number of iterations.
FOR LOOP:=0 TO 100 DO Writeln(LOOP);
REPEAT UNTIL LOOP
A repeat until loop will always execute the code between the KEYWORD REPEAT and UNTIL once. The UNTIL is a post process - do I do it again? line of code.
A:=0; REPEAT Writeln(A); UNTIL A>3; {so you will see 0, 1, 2, 3, 4 then UNTIL fails and continues to the next line of code} Writeln('Finished.');
WHILE EVALUATION_IS_TRUE DO
This is like the REPEAT, UNTIL, except the evaluation is first done then the code in the BLOCK is executed.
A:=0; WHILE (A<4) DO BEGIN Writeln(A); END; Writeln('Finished'); {produces the same output as REPEAT/UNTIL example does!}
GOTO LABEL LOOPING.
Okay, I heard the modern programmers all gasp. As GOTO oddly became a bad style years ago - even though it is the FASTEST jump possible - and it is used in Assembly a lot.
Label DO_AGAIN; Begin A:=0; DO_AGAIN: Writeln(A); If A<4 THEN GOTO DO_AGAIN; Writeln('Finished'); {Produces the same output as the two previous examples} End;