SUBPROGRAM IN PASCAL Function.

Slides:



Advertisements
Presentasi serupa
Pengujian Hipotesis untuk Satu dan Dua Varians Populasi
Advertisements

This document is for informational purposes only. MICROSOFT MAKES NO WARRANTIES, EXPRESS OR IMPLIED, IN THIS DOCUMENT. © 2006 Microsoft Corporation. All.
Algoritma & Pemrograman #10
Mata Kuliah : ALGORITMA dan STRUKTUR DATA 1.
PEMOGRAMAN BERBASIS JARINGAN
TRIP GENERATION.
File Handling.
Procedure pada Pascal ALPROG II
Chapter Nine The Conditional.
PERULANGANPERULANGAN. 2 Flow of Control Flow of Control refers to the order that the computer processes the statements in a program. –Sequentially; baris.
Slide 3-1 Elmasri and Navathe, Fundamentals of Database Systems, Fourth Edition Revised by IB & SAM, Fasilkom UI, 2005 Exercises Apa saja komponen utama.
Prof. Busch - LSU1 Mathematical Preliminaries. Prof. Busch - LSU2 Mathematical Preliminaries Sets Functions Relations Graphs Proof Techniques.
Introduction to The Design & Analysis of Algorithms
IF-ITB/SAS/25Aug2003 IF7074 – Bagian Pertama Page 1 IF 7047 Kewirausahaan Teknologi Informasi Bagian Pertama: 1.1. Entrepreneurship, entrepreneur, dan.
PENGENALAN PL/SQL.
PROSES PADA WINDOWS Pratikum SO. Introduksi Proses 1.Program yang sedang dalam keadaan dieksekusi. 2.Unit kerja terkecil yang secara individu memiliki.
1. Objek dalam kalimat aktif menjadi subjek dalam kalimat pasif
Review Operasi Matriks
Jeff Howbert Introduction to Machine Learning Winter Classification Nearest Neighbor.
DEPARTEMEN ILMU KOMPUTER FMIPA IPB 2011 Praktikum Bahasa Pemrograman.
Functions (Fungsi) Segaf, SE.MSc. Definition “suatu hubungan dimana setiap elemen dari wilayah saling berhubungan dengan satu dan hanya satu elemen dari.
Bilqis1 Pertemuan bilqis2 Sequences and Summations Deret (urutan) dan Penjumlahan.
Risk Management.
VALUING COMMON STOCKS Expected return : the percentage yield that an investor forecasts from a specific investment over a set period of time. Sometimes.
2-Metode Penelitian Dalam Psikologi Klinis
Implementing an REA Model in a Relational Database
MEMORY Bhakti Yudho Suprapto,MT. berfungsi untuk memuat program dan juga sebagai tempat untuk menampung hasil proses bersifat volatile yang berarti bahwa.
3 nd Meeting Chemical Analysis Steps and issues STEPS IN CHEMICAL ANALYSIS 1. Sampling 2. Preparation 3. Testing/Measurement 4. Data analysis 2. Error.
Basisdata Pertanian. After completing this lesson, you should be able to do the following Identify the available group functions Describe the use of group.
Array.
Array Dimensi Banyak Gerlan A. Manu, ST.,MKom
2nd MEETING Assignment 4A “Exploring Grids” Assignment 4 B “Redesign Grids” Create several alternatives grid sysytem using the provided elements: (min.
Function, Procedure, Unit
LOGO Manajemen Data Berdasarkan Komputer dengan Sistem Database.
LIMIT FUNGSI LIMIT FUNGSI ALJABAR.
Lecture 1 Introduction to C# Erick Pranata © Sekolah Tinggi Teknik Surabaya 1.
1 Algoritma Bahasa Pemrograman dan Bab 1.1. Pengertian Algoritma.
Linked List dan Double Linked List
Amortization & Depresiasi
PEMERINTAH KOTA PONTIANAK DINAS PENDIDIKAN PEMERINTAH KOTA PONTIANAK DINAS PENDIDIKAN Jl. Letjen. Sutoyo Pontianak, Telp. (0561) , Website:
BASH – Shell Programming Guide Erick, Joan © Sekolah Tinggi Teknik Surabaya 1.
SMPN 2 DEMAK GRADE 7 SEMESTER 2
VARIABEL DAN OPERATOR.
STRUCTURAL CONTROL continuation STATEMENT  SWITCH  WHILE  DO..WHILE.
Operator dan Assignment Pertemuan 3 Pemrograman Berbasis Obyek Oleh Tita Karlita.
1. 2 Work is defined to be the product of the magnitude of the displacement times the component of the force parallel to the displacement W = F ║ d F.
Lecture 8 Set and Dictionary Sandy Ardianto & Erick Pranata © Sekolah Tinggi Teknik Surabaya 1.
© 2009 Fakultas Teknologi Informasi Universitas Budi Luhur Jl. Ciledug Raya Petukangan Utara Jakarta Selatan Website:
1 Character Strings. 2 Topik String –Representation –Declaration –Functions –Kesalahan Umum –Index char dlm string.
Via Octaria Malau Transfer (Internal Transfers) Transfer (Transfers Internal) Select the account from which funds are to be transferred FROM and then select.
PENJUMLAHAN GAYA TUJUAN PEMBELAJARAN:
Retrosintetik dan Strategi Sintesis
Web Teknologi I (MKB511C) Minggu 12 Page 1 MINGGU 12 Web Teknologi I (MKB511C) Pokok Bahasan: – Text processing perl-compatible regular expression/PCRE.
Lecture 2 Introduction to C# - Object Oriented Sandy Ardianto & Erick Pranata © Sekolah Tinggi Teknik Surabaya 1.
KONTROL ALUR EKSEKUSI PROGRAM
Dasar Pemrograman ARRAY/LARIK.
2. Introduction to Algorithm and Programming
Procedure & Function Sub Program.
SUBPROGRAM IN PASCAL PROCEDURE Lecture 5 CS1023.
1 Diselesaikan Oleh KOMPUTER Langkah-langkah harus tersusun secara LOGIS dan Efisien agar dapat menyelesaikan tugas dengan benar dan efisien. ALGORITMA.
9.3 Geometric Sequences and Series. Objective To find specified terms and the common ratio in a geometric sequence. To find the partial sum of a geometric.
OPERATOR DAN FUNGSI MATEMATIK. Operator  Assignment operator Assignment operator (operator pengerjaan) menggunakan simbol titik dua diikuti oleh tanda.
While … do … Repeat … until … For … to … do …
Kuliah 7 – Pengantar Pemrograman
Dasar-Dasar Pemrograman
Algoritma dan Pemrograman
Algoritma & Pemrograman 1 Achmad Fitro The Power of PowerPoint – thepopp.com Chapter 3.
Algoritma & Pemrograman 1 Achmad Fitro The Power of PowerPoint – thepopp.com Chapter 4.
CMP 131 Introduction to Computer Programming
Draw a picture that shows where the knife, fork, spoon, and napkin are placed in a table setting.
Transcript presentasi:

SUBPROGRAM IN PASCAL Function

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.

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.

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.

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

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.

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

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….

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.

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;

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)

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}

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

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.

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;

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;

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).

FUNCION Triangle ( Angle1, Angle2, Angle3 : Real) :Boolean; Begin If Angle1 + Angle2 + Angle3 -180 = 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.

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.

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.

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>

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.

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

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)31-1-1990 NextDay(<31,12,1990>,1)1/1/1991

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