Algoritma dan Pemrograman Leon Andretti Abdillah

advertisement
Algoritma dan Pemrograman
Leon Andretti Abdillah
14
Subroutine - Methods
1
LeonAbdillah - A&P - Method
18/12/2012 9:43:19
Introduction
 At times, a certain portion of codes has to be used many
times.
 Instead of re-writing the codes many times, it is better to put
them into a "subroutine", and "call" this "subroutine" many
time - for ease of maintenance and understanding.
 Subroutine is called method (in Java) or function (in
C/C++).
 Other terms; predefined process, module, funtion
2
LeonAbdillah - A&P - Method
18/12/2012 9:43:19
Flowchart symbol

3
LeonAbdillah - A&P - Method
18/12/2012 9:43:20
Benefits
 The benefits of using methods are:
1.
2.
3.
4
Divide and conquer: construct the program from simple, small
pieces or components. Modularize the program into selfcontained tasks.
Avoid repeating codes: It is easy to copy and paste, but hard to
maintain and synchronize all the copies.
Software Reuse: you can reuse the methods in other programs,
by packaging them into library codes.
LeonAbdillah - A&P - Method
18/12/2012 9:43:22
Ilustration
 Two parties are involved in using a method: a caller, who calls
the method, and the method to be called.
 The caller passes arguments to the method.
 The method receives these arguments, performs the
programmed operations defined in the method's body, and
returns the result back to the caller.
5
LeonAbdillah - A&P - Method
18/12/2012 9:43:29
Return
6
LeonAbdillah - A&P - Method
18/12/2012 9:43:33
Result
7
LeonAbdillah - A&P - Method
18/12/2012 9:43:34
Example
 Suppose that we need to evaluate the area of a circle many
times, it is better to write a method called getArea(), and reuse it when needed.
8
LeonAbdillah - A&P - Method
18/12/2012 9:43:35
Circle
9
LeonAbdillah - A&P - Method
18/12/2012 9:43:36
Result
10
LeonAbdillah - A&P - Method
18/12/2012 9:43:36
Phytagoras - Two parameters [1/2]
11
LeonAbdillah - A&P - Method
18/12/2012 9:43:37
Phytagoras - Two parameters [2/2]
12
LeonAbdillah - A&P - Method
18/12/2012 9:43:38
Result
13
LeonAbdillah - A&P - Method
18/12/2012 9:43:40
Payroll [1/2]
14
LeonAbdillah - A&P - Method
18/12/2012 9:43:42
Payroll [2/2]
15
LeonAbdillah - A&P - Method
18/12/2012 9:43:43
Result
16
LeonAbdillah - A&P - Method
18/12/2012 9:43:44
Download