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 real
s. 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
© 2007–2010 Hersch, Bear & Company Limited. All rights reserved. “touque.ca,” “Canada’s Thinking Cap,” “Grammar Authority,” and “grammarauthority.com,” are trademarks of Hersch, Bear & Company Limited. All other trademarks and copyrights are the property of their respective owners. | Privacy Policy | Licence to Copy | How to cite | Contact us