Programming – Pascal: Essential skills 4
Learning Outcomes:
- Apply control structures in a solution.
- Sequence, selection and iteration
have been introduced in the Compulsory Part.
Iteration
Methods of iteration:
- for … to … do … / for … downto … do …
- repeat … until …
- while … do …
Advanced technique:
- Nested loop
for … to … do … / for … downto … do …
Important point: use for loop when the number of loops is
known.
for i := 1 to n
do write (i); |
Output: 1234….n
repeat … until …
Important points:
- use repeat loop or while loop when the number of loops cannot be determined before running the program.
- Location of the counter is important.
- The program will run through the content first before checking the condition. i.e. even condition is not met, the content is run at least once.
i := 0; Repeat |
i := 0; Repeat |
Output: 36912 Output:
0369
while … do …
Important points:
- use repeat loop or while loop when the number of loops cannot be determined before running the program.
- Location of the counter is important.
- The program will check the condition first before running through the content i.e. When condition is not met, the content is skipped.
i := 0; while i <10 do i := i + 3; write (i) end; |
i := 0; while i <10 do write (i); i := i + 3 end; |
Output: 36912 Output:
0369
Nested loop
Suppose you have an array A[x,y], you want to sum up the elements.
var i, j
: integer; begin for i
:= 1 to 3 do (* Outer loop *) for
j := 1 to 2 do (* Inner loop *) sum
:= sum + A[i,j] end; |
Use a table to trace the program.
Outer loop |
i |
j |
Inner loop |
1 |
1 |
||
1 |
2 |
||
2 |
1 |
||
2 |
2 |
||
3 |
1 |
||
3 |
2 |
The same applies to nested while loop and nested repeat
loop.
Relevant past paper:
DSE ICT Elect B(SP-2017):
2014 4c*.
No comments:
Post a Comment