Presentasi sedang didownload. Silahkan tunggu

Presentasi sedang didownload. Silahkan tunggu

SUBPROGRAM IN PASCAL Function.

Presentasi serupa


Presentasi berjudul: "SUBPROGRAM IN PASCAL Function."— Transcript presentasi:

1 SUBPROGRAM IN PASCAL Function

2 Pascal Functions In Pascal, a procedure takes inputs (parameters) but does not return a value (except by using reference parameters). A Pascal function takes inputs (parameters) and returns a single value to the calling program. The function name is used to indicate the value returned by the function.

3 Pascal Function Cont’d
Second type o subprogram supported by Turbo Pascal . We have already seen and used some of Pascal’s own functions e.g. Upcase, Length, Sqr, Sqrt. A Function may be viewed as a special type of procedure that returns exactly one result. Functions are declared , called and can be used with variable and value parameters.

4 Pascal Function Cont’d
Functions differ from procedures in that : The return type of a function is included in the function heading, Return type can be any simple data type i.e. REAL, INTEGER, CHAR, BOOLEAN, STRING, an Enumerated type or a subrange type. Within the function body, some value must be assigned to the function name I.e. the return value. Unlike procedure calls, function calls do not appear as separate statements. They are treated as though they were values and so are used in assignment statement, input/output statements and general expressions.

5 Template FUNCTION function_name ( parameter list) : Data_ Type;
e.g. Function Cube (num :integer) :integer; Begin Cube := num * num * num; end;

6 Example program calcCube; function Cube( n : integer) : integer; begin
Cube := n * n * n; end; var number, answer : integer; writeln('Enter a number: '); readln(number); answer := Cube(number); writeln('The cube of ', number, ' is ', answer); end.

7 Recall Mathematical Functions
A function takes one or more inputs and produces a single output for each input or set of inputs. Examples: A function to double the value of the input: d(x) = 2x d(2) = 4 d(17) = 34 A function to cube the value of the input: c(x) = x3 c(2) = 8 c(5) = 125 A function to compute the volume of a cylinder from the radius and height: v(r, h) = p r2h

8 If X, Y, A and B are global variables of type integer, some typical calls might be :
1. X := cube(5); 2. Y := 3* Cube(2) - 10 ; 3. A:= 3, Writeln(cube(A)); 4. If Cube(A) > B then….

9 NOTE: 1. When declaring a function, you must always give the function a data type which indicates the type of the single result. E.g. FUNCTION Sample : INTEGER; or FUNCTION Sample (a:integer;b,c :real) : BOOLEAN; 2. The function code must include a statement that assigns the result to the function name. In this way the function acts as a ‘variable’ in the main program. 3 Use functions when you wish to calculate a single value that will be used in the main program otherwise use procedures.

10 Example Write a function that sums integer elements in an array and returns the value of sum.Incorporate this function into a main program that sums the contents of two arrays. (assume the arrays contain values in the elements and are of equal length) Given the global variables Type array_num = array [1..50] of integer; VAR array1, array2, : array_num; Total : integer;

11 Example (Cont’d) FUNCTION SumArray( A : Array_num): integer; Var
index, sum : integer; Begin sum:= 0; for index := 1 to 50 do sum:= sum + A[index]; SumArray := sum; End; Begin { Main} Total: = SumArray(array1) + SumArray( array2)

12 Example (Cont’d) FUNCTION ValidName ( Name : String) : BOOLEAN; Var
Write a function that indicates if a Name parameter is valid . A name is valid if it contains uppercase characters. Global variable , PersonName type string FUNCTION ValidName ( Name : String) : BOOLEAN; Var index : integer; begin ValidName : = true; For index := 1 to length(Name) do If (Name[index] < ‘A’) OR (Name[index] > ‘Z’) then ValidName := False; end;{ function}

13 Example (cont’d) Begin writeln(‘Enter name’); Readln( PersonName);
If ValidName (PersonName) then writeln(‘Ok’); End.

14 Standard Pascal does not provide a standard power or factorial function.
the function should receive two integers X and N , (where N>= 0) and compute N X Use the approach of multiplying repeatedly by X as we know the number of iterations. The loop will count down to zero fron an initial value of N. For each iteration of the loop X is multiplied by the product.

15 FUNCTION Power ( X, N :integer) : Integer;
Var Result :integer; Begin Result :=1; while N > 0 do result := result * X; N := N-1; End; power : result; end;

16 2. Function to calculate the Factorial e.g. 5 factorial 5x4x3x2x1
FUNCTION Factorial (X : integer) : integer; Var Result : integer; Begin Result := 1; While X > 0 do Result : Result * x; X:= X -1; end; Factorial : result; End;

17 Boolean Function Boolean function can be useful when a branch or loop depends on some complex condition. Rather than code the condition directly into the IF or WHILE statements, can call a Boolean function to form the controlling expression. E.g. If we had a program that works with triangles, the program reads 3 angles . Before performing any calculations on these angles we want to check if they form a triangle ( sum the angles and confirm that they add up to 180).

18 FUNCION Triangle ( Angle1, Angle2, Angle3 : Real) :Boolean;
Begin If Angle1 + Angle2 + Angle = 0 then triangle := true; end; Readln( AngleA, angleB, angleC); If Triangle(( AngleA, angleB, angleC) then writeln (‘the 3 angles form a triangle’); else writeln (‘ the 3 angles do not form a triangle); End.

19 When to use a function There aren’t any formal rules determining when to use a PROCEDURE and when to use a FUNCTION but here are some guidelines 1. If the subprogram must return more than one value or modify the actual parameters, don’t use a FUNCTION 2. If the subprogram must perform input/output, do not use a FUNCTION. 3. If there is only one value returned from the subprogram and it is boolean use a function 4. If there is only one value returned and that value is used immediately in an expression(statement) use a function. 5. When in doubt use a procedure.

20 Multiple Subprogram When a program contains more than one subprogram, they can be called from the main program in any order. One subprogram may call another as long as the subprogram being called appears before the subprogram that calls it. The same identifier names can be used within different subprograms- as they are contained in separate blocks.

21 Exercises Tuliskan fungsi untuk mengkonversikan harga karakter angka (0..9) menjadi harga numerik sesuai dengan karakter yang tertulis. Contoh: ‘8’8, ‘4’4 Tuliskan fungsi IsAnA yang mentest apakah sebuah karakter yang diberikan kepadanya adalah sebuah huruf ‘A’. Harga yang dihasilkan adalah benar jika huruf itu ‘A’,salah jika huruf itu bukan ‘A’. Contoh: IsAnA(‘A’) true IsAnA(‘X’) false Tuliskanlah fungsi, yang jika diberikan sebuah angka Cm yang menyatakan panjang dalam cm, akan menghasilkan pasangan harga <x1,x2> sesuai dengan rumus ukuran metris (1 m = 100 cm) sehingga x1*100+x2 = cm. Contoh: F(100) = <1,0> F(355) = <3,55>

22 Exercises Tuliskan fungsi IsPrima(), yang mentest apakah sebuah bilangan integer yang diberikan merupakan bilangan prima atau bukan. Contoh: IsPrima(2)true, IsPrima(15)false. Tuliskan fungsi IsEven(), yang mentest apakah sebuah bilangan integer yang diberikan merupakan bilangan genap atau bukan. Contoh: IsEven(43)false, IsEven(32)true. Tuliskan fungsi IsOdd(), yang mentest apakah sebuah bilangan integer yang diberikan merupakan bilangan ganjil atau bukan. Contoh: IsOdd(24)false, IsOdd(43)true.

23 Exercises Tuliskanlah sebuah fungsi MAX2, yang menerima masukan dua buah bilangan integer dan menghasilkan sebuah bilangan integer yaitu salah satu diantara nilai dua buah bilangan tersebut yang terbesar. Kemudian, dengan memakai fungsi MAX2, tuliskan sebuah fungsi lain MAX3 yang menghasilkan nilai terbesar dari tiga buah bilangan integer. Contoh: MAX2(1,2)2 MAX2(10,2)10 MAX3(1,2,3) adalah MAX2(MAX2(1,2),3)3 MAX3(10,2,3) adalah MAX3(MAX2(10,2),3)10

24 Exercises Didefinisikan tipe terstruktur untuk mewakili hari seperti dalam kalender yang kita pakai sehari-hari: type nama: DATE<tanggal,bulan,tahun> Tuliskan algoritma untuk: Membaca sebuah tanggal dan sebuah kode bahasa penulisan (1=Inggris, 2=Indonesia, 3=Perancis), Menuliskan tanggal keesokan harinya sesuai dengan kode bahasa. Inggris, DATE ditulis dalam: bulan,’/’,tanggal,’/’,tahun Indonesia, DATE ditulis dalam: tanggal,’-’,bulan,’-’,tahun Perancis, DATE ditulis dalam: tanggal,’/’,bulan,’/’,tahun Proses menghitung hari esok dilakukan oleh sebuah fungsi NextDay yang menerima masukan sebuah tanggal dan menghasilkan tanggal keesokan harinya. Contoh: NextDay(<13,4,1990>,1)4/14/1990 NextDay(<30,1,1990>,2) NextDay(<31,12,1990>,1)1/1/1991

25 Referensi Liem Inggriani, Diktat kuliah IF223 Algoritma dan Pemrograman, Jurusan Teknik Informatika ITB, 1999 DT/266/1, Programming Language, Departement of Computer Science.


Download ppt "SUBPROGRAM IN PASCAL Function."

Presentasi serupa


Iklan oleh Google