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 Studentname : STRINGmark : INTend 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 StudentCardversion '1.0'language Cstructure Studentname : STRINGmark : INTend structurevariable s : structure Studentbegins.name <- "Ada"s.mark <- 15write(s.name, " got ", s.mark, "/20\n")endend algorithm
Output
Ada got 15/20student.aml on GitHubTry itSoonwrite(s) is refused: write the fields one by one.
Structures as parameters
A function can receive a structure and use its fields.
Algorithm RectangleAreaversion '1.0'language Cstructure Rectanglewidth : INTheight : INTend structurefunction area(r : structure Rectangle) : INTbeginreturn r.width * r.heightend functionvariable r : structure Rectanglebeginr.width <- 8r.height <- 5write("Area: ", area(r), "\n")endend algorithm
Output
Area: 40rectangle.aml on GitHubTry itSoonEnums
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.