AlgoML
FR

Arrays

Store several values of the same type, fill an array and go through it.

Declaring an array

variable marks : ARRAY[5] of INT

The size is a positive whole number written directly in the declaration. All the elements have the same type.

Cells are numbered from 1

An array of size 5 has the cells 1, 2, 3, 4 and 5, as in the algorithms written in class. marks[1] is the first element and marks[5] the last one. The index must be an INT.

marks[1] <- 12
write(marks[5], "\n")

C, Java and Python number their cells from 0, so the generator removes 1 from every index: marks[i] becomes marks[i - 1] and marks[j + 1] becomes marks[j]. You write the algorithm with 1 to n, the generated code uses 0 to n - 1. A constant index outside the array, such as marks[0] or marks[6], is refused by the checker.

Filling an array

Give all the values at once with a list between brackets, then go through the array with for i in 1 to size.

Algorithm SumAndMean
version '1.0'
language C
variable marks : ARRAY[5] of INT
variable i : INT
variable total : INT
begin
marks <- [12, 15, 9, 18, 11]
total <- 0
for i in 1 to 5 do
total <- total + marks[i]
end for
write("Sum: ", total, "\n")
write("Mean: ", total div 5, "\n")
end
end algorithm
Output Sum: 65 Mean: 13sum_and_mean.aml on GitHubTry itSoon

Sorting

Bubble sort compares neighbours and swaps them when they are in the wrong order. After each pass, the largest remaining value is at the end.

Algorithm BubbleSort
version '1.0'
language C
variable tab : ARRAY[6] of INT
variable i : INT
variable j : INT
variable tmp : INT
begin
tab <- [5, 2, 9, 1, 7, 3]
for i in 1 to 5 do
for j in 1 to 6 - i do
if tab[j] > tab[j + 1] then
tmp <- tab[j]
tab[j] <- tab[j + 1]
tab[j + 1] <- tmp
end if
end for
end for
for i in 1 to 6 do
write(tab[i], "\n")
end for
end
end algorithm

Exercise

Exercise

Find the largest value of the array [14, 3, 27, 8, 19, 5] without sorting it. Start with values[1] and compare it with the others.

Report a problem with this page