- Pascal 教程
- Pascal - 首页
- Pascal - 概述
- Pascal - 环境设置
- Pascal - 程序结构
- Pascal - 基本语法
- Pascal - 数据类型
- Pascal - 变量类型
- Pascal - 常量
- Pascal - 运算符
- Pascal - 决策
- Pascal - 循环
- Pascal - 函数
- Pascal - 过程
- Pascal - 变量作用域
- Pascal - 字符串
- Pascal - 布尔值
- Pascal - 数组
- Pascal - 指针
- Pascal - 记录
- Pascal - 变体
- Pascal - 集合
- Pascal - 文件处理
- Pascal - 内存
- Pascal - 单元
- Pascal - 日期与时间
- Pascal - 对象
- Pascal - 类
- Pascal 有用资源
- Pascal - 快速指南
- Pascal - 有用资源
- Pascal - 讨论
Pascal - 数组
Pascal 编程语言提供了一种称为数组的数据结构,它可以存储大小固定的相同类型元素的顺序集合。数组用于存储数据集合,但通常更方便地将数组视为相同类型变量的集合。
无需声明单独的变量,例如 number1、number2、… 和 number100,您可以声明一个数组变量,例如 numbers,并使用 numbers[1]、numbers[2]、… 和 numbers[100] 来表示单个变量。数组中的特定元素通过索引访问。
所有数组都由连续的内存位置组成。最低地址对应于第一个元素,最高地址对应于最后一个元素。
请注意,如果您想要从索引 0 开始的 C 风格数组,只需将索引从 1 开始改为 0 即可。
声明数组
要在 Pascal 中声明数组,程序员可以声明类型然后创建该数组的变量,或者直接声明数组变量。
一维数组的类型声明的一般形式为:
type array-identifier = array[index-type] of element-type;
其中:
数组标识符 - 表示数组类型的名称。
索引类型 - 指定数组的下标;它可以是除实数以外的任何标量数据类型。
元素类型 - 指定要存储的值的类型。
例如:
type vector = array [ 1..25] of real; var velocity: vector;
现在,velocity 是一个矢量类型的变量数组,足以容纳最多 25 个实数。
要从索引 0 开始数组,声明将为:
type vector = array [ 0..24] of real; var velocity: vector;
数组下标的类型
在 Pascal 中,数组下标可以是任何标量类型,例如整数、布尔值、枚举或子范围,但实数除外。数组下标也可以具有负值。
例如:
type temperature = array [-10 .. 50] of real; var day_temp, night_temp: temperature;
让我们来看另一个下标为字符类型的例子:
type ch_array = array[char] of 1..26; var alphabet: ch_array;
下标可以是枚举类型:
type color = ( red, black, blue, silver, beige); car_color = array of [color] of boolean; var car_body: car_color;
初始化数组
在 Pascal 中,数组是通过赋值初始化的,可以通过指定特定的下标或使用 for-do 循环来完成。
例如:
type ch_array = array[char] of 1..26; var alphabet: ch_array; c: char; begin ... for c:= 'A' to 'Z' do alphabet[c] := ord[m]; (* the ord() function returns the ordinal values *)
访问数组元素
通过索引数组名称来访问元素。这是通过在数组名称后方方括号中放置元素的索引来完成的。例如:
a: integer; a: = alphabet['A'];
上面的语句将从名为 alphabet 的数组中获取第一个元素并将该值赋给变量 a。
以下是一个例子,它将使用上述三个概念,即声明、赋值和访问数组:
program exArrays;
var
n: array [1..10] of integer; (* n is an array of 10 integers *)
i, j: integer;
begin
(* initialize elements of array n to 0 *)
for i := 1 to 10 do
n[ i ] := i + 100; (* set element at location i to i + 100 *)
(* output each array element's value *)
for j:= 1 to 10 do
writeln('Element[', j, '] = ', n[j] );
end.
编译并执行上述代码后,将产生以下结果:
Element[1] = 101 Element[2] = 102 Element[3] = 103 Element[4] = 104 Element[5] = 105 Element[6] = 106 Element[7] = 107 Element[8] = 108 Element[9] = 109 Element[10] = 110
详细的 Pascal 数组
数组对于 Pascal 非常重要,需要更多详细信息。以下是 Pascal 程序员应该了解的与数组相关的几个重要概念:
| 序号 | 概念与描述 |
|---|---|
| 1 |
多维数组
Pascal 支持多维数组。多维数组最简单的形式是二维数组。 |
| 2 |
动态数组
在这种类型的数组中,初始长度为零。必须使用标准的 SetLength 函数设置数组的实际长度。 |
| 3 |
紧凑数组
这些数组是按位打包的,即每个字符或真值存储在连续的字节中,而不是使用一个存储单元,通常是一个字(4 个字节或更多)。 |
| 4 |
将数组传递给子程序
您可以通过指定数组的名称而不指定索引来将指向数组的指针传递给子程序。 |