Lesson 10 · 10 of 20
for loops with to and downto · Pascal
Count with for in Pascal: to counts up, downto counts down, plus running totals, Char counters and nested loops for cinema seats.

`for i := 1 to 5 do` repeats the statement with i set to 1, 2, 3, 4 and 5: the 7 times table. The counter goes up by one on its own; in fact, the compiler will not let you change it inside the loop.
`downto` counts backwards: 3 downto 1 gives the countdown. Write keeps the numbers on one line and the final WriteLn closes it with the lift-off.
A for goes well with an if: from 1 to 99, only the numbers with i mod 2 = 1, the odd ones, are added up, and the result is 2500. With to, if the start is greater than the end, the loop does not run at all.
The counter can be any ordinal type, including Char: for c := 'A' to 'E' goes through those letters. And a for can sit inside another: for each row i, the inner loop prints its five seats, and together they draw the cinema.
Code · main.pas
program main;var i, total: Integer; c: Char;begin // for ... to counts up, one at a time. for i := 1 to 5 do WriteLn('7 x ', i, ' = ', 7 * i); // downto counts down. for i := 3 downto 1 do Write(i, '... '); WriteLn('Lift-off!'); // Add up the odd numbers from 1 to 99. total := 0; for i := 1 to 99 do if i mod 2 = 1 then total := total + i; WriteLn('Odd numbers up to 99 add up to ', total); // The counter can also be a Char: a grid of cinema seats. for i := 1 to 3 do begin Write('Row ', i, ':'); for c := 'A' to 'E' do Write(' ', i, c); WriteLn; end;end.Output · fpc main.pas && ./main
7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35 3... 2... 1... Lift-off! Odd numbers up to 99 add up to 2500 Row 1: 1A 1B 1C 1D 1E Row 2: 2A 2B 2C 2D 2E Row 3: 3A 3B 3C 3D 3E
Key points
for i := a to b docounts fromatob.downtocounts backwards.- Do not change the counter inside the loop.
- The counter can be an integer, a
Charor another ordinal type.
Exercise
Print the full multiplication table from 1 to 9 with two nested for loops, lining up the results with :4.