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] <- 12write(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 SumAndMeanversion '1.0'language Cvariable marks : ARRAY[5] of INTvariable i : INTvariable total : INTbeginmarks <- [12, 15, 9, 18, 11]total <- 0for i in 1 to 5 dototal <- total + marks[i]end forwrite("Sum: ", total, "\n")write("Mean: ", total div 5, "\n")endend algorithm
Sum: 65 Mean: 13sum_and_mean.aml on GitHubTry itSoonSorting
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 BubbleSortversion '1.0'language Cvariable tab : ARRAY[6] of INTvariable i : INTvariable j : INTvariable tmp : INTbegintab <- [5, 2, 9, 1, 7, 3]for i in 1 to 5 dofor j in 1 to 6 - i doif tab[j] > tab[j + 1] thentmp <- tab[j]tab[j] <- tab[j + 1]tab[j + 1] <- tmpend ifend forend forfor i in 1 to 6 dowrite(tab[i], "\n")end forendend algorithm
1 2 3 5 7 9bubble_sort.aml on GitHubTry itSoonExercise
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.