Arrays, Matrices, and Core Programming Concepts
An array is a collection of elements of the same type, accessed by an index.
var scores : array 1 .. 5 of int
scores(1) := 90
scores(2) := 85
scores(3) := 78
scores(4) := 92
scores(5) := 88
for i : 1 .. 5
put "Score ", i, ":", scores(i)
end for
A matrix is an array with rows and columns (2D array).
var matrix : array 1 .. 3, 1 .. 3 of int
matrix(1,1) := 1
matrix(1,2) := 2
matrix(1,3) := 3
matrix(2,1) := 4
matrix(2,2) := 5
matrix(2,3) := 6
matrix(3,1) := 7
matrix(3,2) := 8
matrix(3,3) := 9
for i : 1 .. 3
for j : 1 .. 3
put matrix(i,j),
end for
put "" % new line
end for
Functions return a value; procedures do not. They help make your code reusable.
procedure greet(name : string)
put "Hello, ", name
end greet
function square(x : int) : int
result := x * x
end square
greet("Alice")
put "5 squared is ", square(5)
Use constants for values that should not change.
const PI : real := 3.1416 put "The value of PI is ", PI
Enumerations define a set of named values.
type Color : enum {Red, Green, Blue}
var myColor : Color
myColor := Green
put myColor
Records store different data types together in one object.
type Student : record
name : string
age : int
grade : int
end record
var s1 : Student
s1.name := "John"
s1.age := 16
s1.grade := 90
put s1.name, " got ", s1.grade
Reading from and writing to files is important for saving data.
var f : int open "scores.txt" for writing as f put f, "90" close f