Sunday, June 13, 2021

Programming – Pascal: Essential skills 4

 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 := i + 3;
                write (i)
until i > 10;

i := 0;

Repeat
                write (i);
                i := i + 3
until i > 10;

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
begin

i := i + 3;

write (i)

end;

i := 0;

while i <10 do
begin

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*.

CE CIT Elect A(2005-2011): 2005 3a-d. 2006 3cd. 2007 2abc. 2009 1bc, 2bii, 4a. 2010 2a.

No comments:

Post a Comment

Syllabus comparison

 Syllabus comparison   DSE ICT 2025 New syllabus DSE ICT 2012-2024 CE CIT 2005-2011 CE CS 1994-2004 ...