Range Over Built in Pascal
On this page
Let’s translate the provided Go code example to Pascal. Here’s the content in Markdown format suitable for Hugo.
Range over Built-in Types
Explanation
range
iterates over elements in a variety of built-in data structures. Let’s see how to use range
with some of the data structures we’ve already learned.
Code Example
Explanation
Here we use a loop to sum the numbers in an array. Arrays work like this too.
nums
is defined as an array of integers. We initialize it with values 2, 3, and 4.
We use a for loop to iterate over the array, summing the values, and then print the result.
On arrays, we often need both the index and value for each entry. In some cases, we might only want the index.
We use another for loop to check for the value 3 in the array and print its index when found.
TStringList
is Pascal’s way of handling key-value data structures similar to maps in other languages.
We create a TStringList
named kvs
, add some key-value pairs, and then iterate over the list to print each key and its corresponding value.
We can also iterate over just the keys of a map.
Finally, we use a simple for loop to iterate over characters in a string. Pascal treats strings as arrays of characters, and we can print both the index and the ASCII value of each character.