程序是子程序,它不是返回单个值,而是允许获得一组结果.
在Pascal中,使用过程关键字定义过程.过程定义的一般形式如下 :
procedure name(argument(s): type1, argument(s): type 2, ... ); < local declarations > begin < procedure body > end;
Pascal中的过程定义包含标题,本地声明和身体的程序.过程标题包含关键字过程和过程的名称.以下是程序的所有部分 :
参数 : 参数建立了调用程序和过程标识符之间的联系,也称为形式参数.程序中参数的规则与函数的参数规则相同.
本地声明 : 本地声明是指标签,常量,变量,函数和程序的声明,仅适用于程序正文.
程序身体 : 过程体包含一组语句,用于定义过程的作用.它应始终包含在保留字开头和结尾之间.它是完成所有计算的过程的一部分.
以下是名为 findMin的过程的源代码( )的.此过程采用4个参数x,y,z和m,并将前三个变量中的最小值存储在名为m的变量中.变量m由引用传递(我们将在稍后讨论通过引用传递参数) :
procedure findMin(x, y, z: integer; var m: integer); (* Finds the minimum of the 3 values *) begin if x < y then m := x else m := y; if z <m then m := z; end; { end of procedure findMin }
程序声明告诉编译器关于过程名称以及如何调用过程.过程的实际主体可以单独定义.
过程声明具有以下语法 :
procedure name(argument(s): type1, argument(s): type 2, ... );
请注意,程序名称与任何类型无关.对于上面定义的过程 findMin(),以下是声明 :
procedure findMin(x, y, z: integer; var m: integer);
创建过程时,您可以定义过程必须执行的操作.要使用该过程,您必须调用该过程来执行定义的任务.当程序调用过程时,程序控制将转移到被调用的过程.被调用的过程执行定义的任务,当到达其最后结束语句时,它将控制返回给调用程序.
要调用过程,您只需传递所需的参数以及程序名称如下所示 :
program exProcedure; var a, b, c, min: integer; procedure findMin(x, y, z: integer; var m: integer); (* Finds the minimum of the 3 values *) begin if x < y then m:= x else m:= y; if z < m then m:= z; end; { end of procedure findMin } begin writeln(' Enter three numbers: '); readln( a, b, c); findMin(a, b, c, min); (* Procedure call *) writeln(' Minimum: ', min); end.
编译并执行上述代码时,会产生以下结果 :
Enter three numbers: 89 45 67 Minimum: 45
我们已经看到程序或子程序可能会调用另一个子程序.当子程序调用自身时,它被称为递归调用,该过程称为递归.
为了说明这个概念,让我们计算一个数的阶乘.数字n的阶乘定义为 :
n! = n*(n-1)! = n*(n-1)*(n-2)! ... = n*(n-1)*(n-2)*(n-3)... 1
以下程序通过递归调用自身来计算给定数字的阶乘.
program exRecursion; var num, f: integer; function fact(x: integer): integer; (* calculates factorial of x - x! *) begin if x=0 then fact := 1 else fact := x * fact(x-1); (* recursive call *) end; { end of function fact} begin writeln(' Enter a number: '); readln(num); f := fact(num); writeln(' Factorial ', num, ' is: ' , f); end.
编译并执行上述代码时,会产生以下结果 :
Enter a number: 5 Factorial 5 is: 120
以下是另一个例子,它产生 Fibonacci Series 使用递归函数给定给定数字 :
program recursiveFibonacci; var i: integer; function fibonacci(n: integer): integer; begin if n=1 then fibonacci := 0 else if n=2 then fibonacci := 1 else fibonacci := fibonacci(n-1) + fibonacci(n-2); end; begin for i:= 1 to 10 do write(fibonacci (i), ' '); end.
编译并执行上述代码时,会产生以下结果 :
0 1 1 2 3 5 8 13 21 34
如果是子程序(函数或过程)是使用参数,它必须声明接受参数值的变量.这些变量称为子程序的形式参数.
形式参数的行为与子程序中的其他局部变量相似,并在进入子程序时创建并销毁在退出时.
在调用子程序时,有两种方法可以将参数传递给子程序 :
Sr.No | 呼叫类型&描述 |
---|---|
1 | 按值调用 此方法将参数的实际值复制到子程序的形式参数.在这种情况下,对子程序中的参数所做的更改对参数没有影响. |
2 | 参考 此方法将参数的地址复制到形参中.在子程序内,该地址用于访问调用中使用的实际参数.这意味着对参数所做的更改会影响参数. |
默认情况下,Pascal使用按值调用传递参数.通常,这意味着子程序中的代码不能改变用于调用子程序的参数.我们在"Pascal - Functions"一章中使用的示例程序使用按值调用调用名为max()的函数.
然而,这里提供的示例程序( exProcedure )使用按引用调用调用过程findMin().