Csc211 2023 Class - Iteration
Csc211 2023 Class - Iteration
PROGRAMMING
in PASCAL
CSC211
ITERATION STATEMENTS
ITERATION STATEMENTS
•FOR - DO
•WHILE-DO
•REPEAT-UNTIL
•Iteration in programming
means REPEATING steps, or
instructions, over and over
again. This is often called a
‘LOOP’.
•ITERATION continues as long as
the condition remains TRUE. It
stops when the condition
becomes FALSE except on
exceptional cases.
ITERATION STATEMENT
FLOWCHART
TRUE
CONDITION
FALSE
FOR and
WHILE
CONDITION FALSE
TRUE
STATEMENT(S)
STATEMENT(S)
REPEAT - UNTIL
CONDITION TRUE
FALSE
ALGORITHM
The algorithm used is as follows:
1. Initialize the counter to zero.
2. Increment the counter by 1.
3. Test the counter to see if it is
less than or equal to
MAXIMUM VALUE. WHEN IT
IS TRUE STEP 4 OTHERWISE
STEP 5
4. Perform the statement.
GOTO STEP 2
5. EXIT LOOP
The FOR Loop
The general form of the FOR
construct is as follows:
where:
i. variable is the loop counter,
ii. expression-1 is the initial
value, and
iii. expression-2 is the final
value.
FOR K := 1 TO 5 DO
WRITELN(‘Hello World’);
PROGRAM ForLoop(OUTPUT);
USES CRT;
VAR
counter :INTEGER;
BEGIN
FOR counter := 1 TO 5 DO
WRITELN('Hello World..’);
WRITELN;
WRITELN('Press ENTER to continue');
READLN
END.
PROGRAM Loop1(input,output);
USES CRT;
VAR K,N :INTEGER;
BEGIN
READLN(N);
FOR K := 1 TO N DO WRITELN(K);
WRITELN('Press ENTER to continue..’);
READLN
END.
PROGRAM Loop2(input,output);
USES CRT;
VAR K,N :INTEGER;
BEGIN
READLN(N);
FOR K := 1 TO N DO
BEGIN
WRITE('Number is = ');
WRITELN(K);
END;
WRITELN('Press ENTER to continue..');
READLN
END.
The WHILE Loop
WHILE condition DO statement;
PROGRAM Loop3(input,output);
USES CRT;
VAR K,N :INTEGER;
BEGIN
N:=10;
K:=1;
WHILE K <= N DO
BEGIN
WRITELN('Number ',K);
K := K+1;
END;
WRITELN('Press ENTER to continue..’);
READLN
END.
𝑺𝑼𝑴 = 𝑿 ∗ 𝑲
𝑲=𝟏
FOR statement
HINT:
The program should assign values
to the following variables: N and X.
The value of K ranges from 1 to N
The REPEAT Loop
REPEAT
statement-1;
statement-2;
...
statement-n;
UNTIL condition;
𝑺𝑼𝑴 = 𝑿 ∗ 𝑲
𝑲=𝟏
HINT:
The program should assign values
to the following variables: N and X.
The value of K ranges from 1 to N
NESTED LOOPS
Loops can be used inside another loop.
In this case it is said that the inner loop
is nested inside the outer loop.
You can nest as many loops as you wish
inside one another, according to your
application.
LOOPS AND NESTED LOOPS ARE VERY
USEFUL IN ARRAY / MATRICES
PROGRAMMING.
PROGRAM NestedLoops(OUTPUT);
USES CRT;
VAR
Row, Column :INTEGER;
BEGIN
FOR Row := 1 TO 3 DO
BEGIN
FOR Column := 1 to 5 DO
WRITE(Column, ' ');
WRITELN
END;
READLN
END.
WHAT DOES THIS PROGRAM DO?
PROGRAM Loop1(input,output);
USES CRT;
VAR I,J :INTEGER;
BEGIN
FOR I := 1 TO 6 DO
BEGIN
FOR J := 1 TO I DO
WRITE('*’);
WRITELN;
END;
FOR I := 6 DOWNTO 1 DO
BEGIN
FOR J := I DOWNTO 1 DO
WRITE('*’);
WRITELN;
END;
WRITELN('Press ENTER to
continue..');
READLN
END.
DRILL 2: NESTED LOOPS