touque.ca > Education Commons > Programming: Concepts > Arrays > Substrings

Concepts

Arrays

In general, each variable can hold only a single value: one int, real, char, string, or boolean.

But often we want to process multiple instances of a single datatype. For example, if we were gathering the marks for a class, we might need 20, 30, or more reals. Not only would it be tedious to create 20, 30, or more real variables, each with a different name, it would be difficult to process them efficiently in a loop.

Instead, we can create a special kind of variable—an array—which assigns a single name to multiple locations in RAM. The computer distinguishes amongst these multiple locations with an index into the array.

Using both the array name and its index, we can refer to each location individually. And because the array index is always an integer value, we can use a counter (or other integer variable) to “step through” the array.

Sample code

% Declaration Section

const ARRAY_LIMIT := 10

var mark : array 1 .. ARRAY_LIMIT of real
var markIndex : int
var sum : real


% Initialization section

sum := 0
markIndex := 1


% Event-processing section

loop

   put "mark? " ..
   get mark (markIndex)

   sum := sum + mark (markIndex)

   markIndex := markIndex + 1

   exit when markIndex > ARRAY_LIMIT

end loop


% Results section

put skip, "sum of marks: ", sum : 0 : 1

touque.ca > Education Commons > Programming: Concepts > Arrays > Substrings