AlgoML
FR

Structures and enums

Group related data into one record, and give names to a set of values.

Structures

A structure groups several values, called fields, under one name. Declare it before begin:

structure Student
name : STRING
mark : INT
end structure

Then declare variables of that type with the word structure:

variable s : structure Student

Using the fields

Read or change a field with a dot: s.name, s.mark.

Algorithm StudentCard
version '1.0'
language C
structure Student
name : STRING
mark : INT
end structure
variable s : structure Student
begin
s.name <- "Ada"
s.mark <- 15
write(s.name, " got ", s.mark, "/20\n")
end
end algorithm
Output Ada got 15/20student.aml on GitHubTry itSoon

write(s) is refused: write the fields one by one.

Structures as parameters

A function can receive a structure and use its fields.

Algorithm RectangleArea
version '1.0'
language C
structure Rectangle
width : INT
height : INT
end structure
function area(r : structure Rectangle) : INT
begin
return r.width * r.height
end function
variable r : structure Rectangle
begin
r.width <- 8
r.height <- 5
write("Area: ", area(r), "\n")
end
end algorithm

Enums

An enum gives names to a fixed list of values:

enum Level { Beginner, Intermediate, Advanced }
variable level : enum Level

An enum variable can be used in a switch. Each value appears only once in the list.

Exercise

Exercise

Declare a structure Rectangle with a width and a height, then write a function that returns its area.

Report a problem with this page