Information Technology Topic
Loops in Pascal
- Read notes
- Flashcards
- Quiz
- Confident
Study focus - 3 things
- A while loop tests its condition first and repeats while it is TRUE, so it may run zero times; a repeat..until loop tests last and stops when its condition becomes TRUE, so it always runs at least once
- A for loop counts for you: for day := 1 to 5 do runs the body 5 times, adding 1 to day after each pass, and runs zero times if the start is already past the end
- Only the first statement after do belongs to a while or for loop unless begin and end group several statements, and a loop must change something that eventually makes it stop
Section 1Why programs need loops
A program often has to do the same job again and again: add up the fare of every passenger on a bus, ask for the mark of every pupil in a class, count down the seats left in a hall. Typing the same lines fifty times would be slow and error-prone, so we put them in a loop. A loop is a set of statements that is repeated. In a flowchart a loop shows up as a branch from a decision box that leads back to an earlier step. In pseudocode you have already met While and For. Pascal has three loops: while..do, repeat..until and for..to..do. All three repeat statements. They differ in WHEN they test and HOW they count. Here's the trick: ask three questions. Do I know how many times? Use for. Might it need to run zero times? Use while. Must it run at least once? Use repeat.
Section 2The while loop: test first
The idea in pseudocode: Store 1 in count While count <= 5 Display count Store count + 1 in count End While A while loop has four parts: give the control variable a starting value, test it, do the action, and update the control variable so that the test can eventually fail. The same idea as Pascal-style code: program CountUp; var count : integer; begin count := 1; while count <= 5 do begin writeln(count); count := count + 1 end end. It displays 1, 2, 3, 4 and 5, each on its own line. The body runs 5 times, but the condition is tested 6 times: the sixth test (count is 6) is the one that fails and ends the loop. The test comes first, so if the condition is FALSE at the start the body never runs. With count := 10 and while count <= 5 do, nothing is displayed.
Section 3The repeat..until loop: test last
A repeat loop runs the body first and tests afterwards, so the body always runs at least once. Pascal-style code: program CountDown; var seats : integer; begin seats := 3; repeat writeln(seats); seats := seats - 1 until seats = 0 end. It displays 3, 2 and 1. The body ran 3 times and the condition was tested 3 times, after each pass. Watch out: until stops the loop when its condition is TRUE. That is the opposite of while, which carries on while its condition is TRUE. A while loop that continues while count < 10 becomes repeat ... until count >= 10. repeat and until already mark the start and end of the body, so you do not need begin and end. Same start, different result. With n := 10, the loop while n <= 5 do shows nothing, but repeat writeln(n); n := n + 1 until n > 5 shows 10 once.
Section 4The for loop: counting
Use for when you know how many times the steps must repeat. In Pascal-style code: for day := 1 to 5 do writeln('Day ', day) The loop variable day starts at 1. After each pass it goes up by 1 on its own, and the loop ends after the pass where day is 5. That is 5 passes, because both ends are included. The statement does the start, the test and the update for you. If the start is already past the end, as in for day := 5 to 1 do, the body does not run at all. To count down, use downto: for count := 3 downto 1 do runs for 3, 2 and 1. The loop variable must be an ordinal type such as integer (a real number is not allowed), and your own statements must not change it inside the loop. Let the for statement do that. Its value is not defined once the loop has finished, so do not rely on it afterwards. Easy to mix up: for day := 1 to 5 runs 5 times, but for day := 0 to 5 runs 6 times, because 0 is counted too.
Section 5Which statements belong to the loop?
A while loop or a for loop repeats ONE statement. To repeat several, group them with begin and end. A group like that is called a compound statement. Compare these two Pascal-style pieces. for i := 1 to 3 do writeln('Hello'); writeln('Bye') This displays Hello three times and then Bye once, because only the first writeln is inside the loop. for i := 1 to 3 do begin writeln('Hello'); writeln('Bye') end This displays Hello and Bye three times each: Hello, Bye, Hello, Bye, Hello, Bye. Indenting the second line does not put it inside the loop. Only begin and end do that, and the same rule applies to a while loop.
Section 6Tracing a loop and choosing the right one
To follow a loop, write down the variables after every pass. For the CountUp program: Start: count is 1 Pass 1: shows 1, count becomes 2 Pass 2: shows 2, count becomes 3 Pass 3: shows 3, count becomes 4 Pass 4: shows 4, count becomes 5 Pass 5: shows 5, count becomes 6 Test: 6 <= 5 is FALSE, so the loop stops. Passes and tests are different counts. A while loop that runs n passes tests its condition n + 1 times. A repeat loop that runs n passes tests n times. Choosing: known number of times, use for. Unknown number of times, and possibly none, use while. Unknown number of times, but at least one, use repeat, for example asking for a mark again until it is valid.
Section 7Loops that never end, and loops that stop early
An infinite loop never stops. The usual causes, shown with Pascal-style lines: - The update is missing, so the control variable never changes. - The update is outside the loop because begin and end are missing. In while count <= 5 do writeln(count); count := count + 1 only the writeln repeats, so count stays at 1 for ever. - A repeat condition can never become TRUE. In n := 1 followed by repeat n := n + 2 until n = 6, n goes 1, 3, 5, 7 and skips over 6. Off-by-one slips are the opposite problem: the loop runs one time too many or too few. Check whether the end value is included (to is, so for i := 1 to 5 runs 5 times) and whether you meant < or <=. Here's the trick: before running any loop, say out loud what changes each pass and which change will finally make the condition stop it.
Examples
A tuck shop in Portmore records how many patties it sells from Monday to Friday. This Pascal-style program reads the five daily figures and adds them up. The figures typed are 12, 8, 15, 10 and 9. program WeekTotal; var day : integer; sold : integer; total : integer; begin total := 0; for day := 1 to 5 do begin readln(sold); total := total + sold end; writeln('Total sold: ', total) end. (a) State how many times the loop body runs and why a for loop suits this job. (b) Show the values of day, sold and total after each pass. (c) State the line that is displayed. (d) The shop will open for 6 days next term. State the one change needed.
(a) The body runs 5 times, for day equal to 1, 2, 3, 4 and 5. A for loop suits the job because the number of days is known before the loop starts. (b) Pass 1: day 1, sold 12, total 12. Pass 2: day 2, sold 8, total 20. Pass 3: day 3, sold 15, total 35. Pass 4: day 4, sold 10, total 45. Pass 5: day 5, sold 9, total 54. (c) Total sold: 54 (d) Change the 5 to 6 in the loop heading, giving for day := 1 to 6 do. Six figures are then read.
A pupil in Mandeville has 450 dollars saved and puts away 300 dollars every week until she has at least 2000 dollars. program SavingsGoal; const goal = 2000; weekly = 300; var saved : integer; weeks : integer; begin saved := 450; weeks := 0; while saved < goal do begin saved := saved + weekly; weeks := weeks + 1 end; writeln('Weeks needed: ', weeks); writeln('Saved: ', saved) end. (a) Trace saved and weeks after each pass. (b) State the two lines displayed and how many times the condition is tested. (c) Rewrite the loop with repeat..until and say whether it gives the same result. (d) Another pupil already has 2500 dollars saved. State what the while version and the repeat version display, and say which is right.
(a) Start: saved 450, weeks 0. Pass 1: 750, 1. Pass 2: 1050, 2. Pass 3: 1350, 3. Pass 4: 1650, 4. Pass 5: 1950, 5. Pass 6: 2250, 6. (b) Weeks needed: 6 and Saved: 2250. The condition is tested 7 times: 6 times it is TRUE and the seventh time (2250 < 2000) it is FALSE. (c) repeat saved := saved + weekly; weeks := weeks + 1 until saved >= goal. The stop condition is the opposite of the while condition. It gives the same result here, Weeks needed: 6 and Saved: 2250, because 450 is below the goal so one pass was needed anyway. (d) The while version displays Weeks needed: 0 and Saved: 2500, which is right because nothing needs saving. The repeat version always runs once, so it displays Weeks needed: 1 and Saved: 2800, which is wrong. When the loop may need to run zero times, use while.
Now let's water it
Session runs notes to flashcards to quiz back-to-back.
Where this comes from
- CSEC Information Technology Syllabus (CXC 30/G/SYLL 08, revised 2000, 2008, 2013) · Caribbean Examinations Council (CXC) · Section 3, Specific Objective 8 · Syllabus scope
- Free Pascal Reference guide v3.2.2 (16.1 Programs, 16.5 Blocks and the language pages in the facts sheet), RTL entries Write, Writeln, ReadLn, and User's guide 3.2 and Appendix D · Free Pascal team · Chapter 13, The while..do statement (13.2.7), checked against (https://www.freepascal.org/docs-html/ref/refsu61.html) · Facts
- Free Pascal Reference guide v3.2.2 (16.1 Programs, 16.5 Blocks and the language pages in the facts sheet), RTL entries Write, Writeln, ReadLn, and User's guide 3.2 and Appendix D · Free Pascal team · Chapter 13, The repeat..until statement (13.2.6), checked against (https://www.freepascal.org/docs-html/ref/refsu60.html) · Facts
- Free Pascal Reference guide v3.2.2 (16.1 Programs, 16.5 Blocks and the language pages in the facts sheet), RTL entries Write, Writeln, ReadLn, and User's guide 3.2 and Appendix D · Free Pascal team · Chapter 13, The for..to/downto..do statement (13.2.4), checked against (https://www.freepascal.org/docs-html/ref/refsu58.html) · Facts
- Free Pascal Reference guide v3.2.2 (16.1 Programs, 16.5 Blocks and the language pages in the facts sheet), RTL entries Write, Writeln, ReadLn, and User's guide 3.2 and Appendix D · Free Pascal team · Chapter 13, Compound statements (13.2.1), checked against (https://www.freepascal.org/docs-html/ref/refsu55.html) · Facts
- Navy Electricity and Electronics Training Series (NEETS), Module 22, Introduction to Digital Computers (NAVEDTRA 14194, September 1998) · US Navy (Naval Education and Training Professional Development and Technology Center) · Chapter 3, Fundamental flowcharting symbols (p. 3-17; the decision symbol has a YES and a NO branch, and a NO branch can lead back so that a processing block is performed again; 1998 US Navy text), checked against (https://vtda.org/bits/other/US_Navy/NEETS/US%20Navy%20NEETS%20-%20Module%2022-Introduction%20to%20Digital%20Computers%20NAVEDTRA%2014194.pdf) · Facts