Lesson 11 · 11 of 20
Static arrays · Pascal
Store several values of the same type in a Pascal array: a week of temperatures, with the average and the hottest day.

An array holds several values of the same type under one name. It is declared with its indexes: array[1..7] of Integer is seven integers numbered 1 to 7. It is static: its size is fixed when the program is compiled and never changes.
Days is a constant array, with its values in brackets, and temps is a variable that starts with the week's temperatures. Each element is reached by its index in square brackets: temps[4] := 20 corrects Thursday.
`Low` and `High` give the first and last index, and `Length` the number of elements. With them the for loop walks the array without hard-coded numbers, and keeps working if the size changes.
Inside the loop three things happen: each day is printed with its temperature, added to total, and hottest remembers the index of the hottest day so far. At the end, total / Length(temps) gives the average.
Using an index that does not exist, such as temps[8], is a mistake. With a constant index the compiler already warns you; with a variable, turn on run-time checking with {$R+} at the top of the program.
Code · main.pas
program main;// A constant array: the names of the days.const Days: array[1..7] of String = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun');// A variable array of 7 integers, with initial values.var temps: array[1..7] of Integer = (18, 21, 24, 19, 26, 28, 22); i, hottest, total: Integer;begin temps[4] := 20; // change one element total := 0; hottest := 1; // Low and High give the first and last index. for i := Low(temps) to High(temps) do begin WriteLn(Days[i], ': ', temps[i]:3, ' C'); total := total + temps[i]; if temps[i] > temps[hottest] then hottest := i; end; WriteLn('Average: ', total / Length(temps):0:1, ' C'); WriteLn('Hottest day: ', Days[hottest], ' (', temps[hottest], ' C)');end.Output · fpc main.pas && ./main
Mon: 18 C Tue: 21 C Wed: 24 C Thu: 20 C Fri: 26 C Sat: 28 C Sun: 22 C Average: 22.7 C Hottest day: Sat (28 C)
Key points
array[1..7] of Integerdeclares seven integers.a[i]reads or changes elementi.Low,HighandLengthgive the bounds and the size.- A static array never changes size.
Exercise
Add a rain array with the litres of rain for each day and print how many days it rained and which day was the wettest.