04/10/2014
1
Algoritma dan FlowchartAngga Akbar Fanani
1
Problem
• Pertanyaan atau tugas yang kita cari jawabandan/atau penyelesaiannya
2
We "just do" Guesswork-and-luck
Experience (possibly
someone else's)
Trial-and-error Scientifically"
HOW DO WE SOLVE PROBLEMS?
04/10/2014
2
The Problem-solving Process
3
Problem specification
Algorithm
Program
Executable (solution)
Design
Implementation
Compilation
Analysis
The Problem-solving Process
Problem specification
Algorithm
Program
Executable (solution)
Analysis
Design
Implementation
Compilation
“Doctor, my head hurts“
Patient has elevated pressure in anterior parietal lobe
1. Sterilize cranial saw2. Anaesthetize patient
3. Remove top of skull4. Get the big spoon...5. etc., etc.
sterilize(saw,alcohol);raise_hammer();lower hammer(fast);start(saw);/* etc. etc. */0100111010110010101010101001010101010100
11001010101010100101101001110101010101
001001011101001111010101011111010101000110100001101...
4
04/10/2014
3
5
Definisi Algoritma
• Algoritma adalah urutan langkah logis tertentu untuk memecahkan suatu masalah▫ Urutan langkah logis, yang berarti algoritma harus
mengikuti suatu urutan tertentu, tidak boleh melompat-lompat
• Alur pemikiran dalam menyelesaikan suatu pekerjaan yang dituangkan secara tertulis.▫ Alur pikiran, sehingga algoritma seseorang dapat
juga berbeda dari algoritma orang lain▫ Tertulis, yang artinya dapat berupa kalimat,
gambar, atau tabel tertentu
6
04/10/2014
4
Definisi Algoritma
• Deretan langkah-langkah komputasi yang mentransformasikan data masukan menjadi keluaran
• Deretan instruksi yang jelas untuk memecahkan masalah, yaitu untuk memperoleh keluaran yang diinginkan dari suatu masukan dalam jumlah waktu yang terbatas
• Prosedur komputasi yang terdefinisi dengan baik yang menggunakan beberapa nilai sebagai masukan dan menghasilkan beberapa nilai yang disebut keluaran.
7
Sejarah Algoritma
• Asal kata algoritma berasal dari nama Abu Ja’far Mohammed Ibn Musa al-Khowarizmi▫ Ilmuan Persia yang menulis kitab al jabar wal-
muqabala (the book of restoration and reduction)▫ Tahun 825 M
• Perubahan kata▫ Algorism proses menghitung dengan angka Arab▫ Algorist orang yang menggunakan angka Arab▫ Algorithm metode perhitungan secara umum
• Tahun 1950 euclid’s algorithm▫ Langkah-langkah menemukan pembagi bersama
terbesar (common greatest divisor = gcd)
8
04/10/2014
5
Ciri Algoritma (Donald E. Knuth)
• Finiteness: Algoritma harus berhenti setelah mengerjakan sejumlah langkah terbatas
• Definiteness: Setiap langkah harus didefinisikan secara tepat dan tidak berarti-dua (ambiguous)
• Algoritma memiliki nol atau lebih masukan (input)
• Algoritma memiliki nol atau lebih keluaran (output)
• Effectiveness: Algoritma harus efektif, setiap langkah harus sederhana sehingga dapat dikerjakan dalam sejumlah waktu yang masuk akal
9
Algorithm -- Examples
• A cooking recipe• Assembly instructions for a model• The rules of how to play a game• VCR instructions• Description of a martial arts technique• Directions for driving from A to B• A knitting pattern• A car repair manual
10
04/10/2014
6
Almond and Honey Slice
1/2 quantity Shortcrust Pastry
185 g unsalted butter
100 g castor sugar
5 tablespoons honey
50 ml cream
50 ml brandy or any other liqueur or spirit
300 g flaked almonds
Preheat oven for 200° C
Line a 30 cm 20 cm baking tray with baking paper, and then with pastry
Bake blind for 20 minutes, then remove weights and foil
Turn oven up to 220° C.
Bring remaining ingredients to a boil, stirring.
Spread evenly over pastry.
Bake until topping is bubbling and has caramelised evenly, about 15 minutes.
Cool before cutting into fingers or squares.
11
From: Stephanie Alexander, The Cook’s Companion, Viking/Penguin, Ringwood, Victoria, 1996, p. 349.
Almond and Honey Slice
1/2 quantity Shortcrust Pastry
185 g unsalted butter
100 g castor sugar
5 tablespoons honey
50 ml cream
50 ml brandy or any other liqueur or spirit
300 g flaked almonds
Preheat oven for 200° C
Line a 30 cm 20 cm baking tray with baking paper, and then with pastry
Bake blind for 20 minutes, then remove weights and foil
Turn oven up to 220° C.
Bring remaining ingredients to a boil, stirring.
Spread evenly over pastry.
Bake until topping is bubbling and has caramelised evenly, about 15 minutes.
Cool before cutting into fingers or squares.
12
From: Stephanie Alexander, The Cook’s Companion, Viking/Penguin, Ringwood, Victoria, 1996, p. 349.
Instructions are given in the order in which they are performed (“executed”)
04/10/2014
7
Correct Algorithm?Cut chicken into pieces
and brown the pieces on all sides in a casserole dish in hot olive oil.
Remove the chicken and to the juices in the casserole add garlic, onions and green peppers, and sauté until onion is golden.
Add bay leaf, whole tomatoes, and chicken broth.
When the broth boils add salt, saffron and rice.
Arrange chicken on rice, cover casserole and bake in a moderate oven (350°F) for 20 minutes or until the rice is tender.
Add beans and artichokes during last 10 minutes of cooking.
13
From: “Arroz Con Pollo” in The Margaret Fulton Cookbook, Hamlyn, Sydney, 1968.
Correct Algorithm?Cut chicken into pieces
and brown the pieces on all sides in a casserole dish in hot olive oil.
Remove the chicken and to the juices in the casserole add garlic, onions and green peppers, and sauté until onion is golden.
Add bay leaf, whole tomatoes, and chicken broth.
When the broth boils add salt, saffron and rice.
Arrange chicken on rice, cover casserole and bake in a moderate oven (350°F) for 20 minutes or until the rice is tender.
Add beans and artichokes during last 10 minutes of cooking.
14
From: “Arroz Con Pollo” in The Margaret Fulton Cookbook, Hamlyn, Sydney, 1968.
04/10/2014
8
Correct Algorithm?Cut chicken into pieces
and brown the pieces on all sides in a casserole dish in hot olive oil.
Remove the chicken and to the juices in the casserole add garlic, onions and green peppers, and sauté until onion is golden.
Add bay leaf, whole tomatoes, and chicken broth.
When the broth boils add salt, saffron and rice.
Arrange chicken on rice, cover casserole and bake in a moderate oven (350°F) for 10 minutes.
Add beans and artichokes.
Cover, and bake for another 10 minutes or until rice is tender.
15
Correct algorithm ???...
16
04/10/2014
9
Correct algorithm
17
Values
• Represent quantities, amounts or measurements
• May be numerical or alphabetical(or other things)
• Often have a unit related to their purpose
• Example:▫ Recipe ingredients
18
04/10/2014
10
Variables
• Are containers for values – places to store values
• Example:
19
This jar
can contain
10 cookies
50 grams of sugar
3 slices of cake
etc.
ValuesVariable
Restrictions on Variables
• Variables may be restricted to contain a specific type of value
20
04/10/2014
11
Instructions (Primitives)
• Some action that is ▫ simple
▫ unambiguous
▫ that the system knows about...
▫ ...and should be able to actually do
21
Instructions – Examples
• Take off your shoes
• Count to 10
• Cut along dotted line
• Knit 1
• Purl 2
• Pull rip-cord firmly
• Sift 10 grams of arsenic
22
Directions to perform specific actions on valuesand variables
04/10/2014
12
Instructions -- Application
• Some instructions can only be applied to a specific type of values or variables
• Examples:
23
Instructions (Primitives) --Recommendations• When writing an algorithm, make each
instruction simple and unambiguous
• Example:
24
Cut chicken into pieces and brown the pieces on all sides in a casserole dish in hot olive oil.
Cut chicken into pieces.Heat olive oil in a casserole
dish.Brown the chicken pieces in
the casserole dish.
04/10/2014
13
Instructions (Primitives)
• When writing an algorithm, make each instruction simple and unambiguous
• Example:
25
Cut chicken into pieces and brown the pieces on all sides in a casserole dish in hot olive oil.
Cut chicken into pieces.Heat olive oil in a casserole
dish.Brown the chicken pieces in
the casserole dish.
A “sequence” of simple instructions
Function
• A named sequence of instructions
• So that you can▫ Refer to it collectively (by name)
▫ ...instead of individually (by each instruction in the sequence)
• Example:
▫ Drive_To_Uni
26
04/10/2014
14
Function -- Examplefunction Drive_To_Uni{
1. find car keys2. disable car alarm3. open car door
4. get in car5. shut car door6. put keys in ignition7. start car8. back car out of
driveway9. drive to end of street
10. turn right11. drive to end of street12. turn left...etc...etc...etc
27
...etc...etc...etc...52. find parking space53. pull into parking
space54. turn off engine55. remove keys from
ignition56. open car door57. get out58. shut car door59. lock car door60. enable alarm
}
Function – Example
function Do_Wednesday{
Wake_upHave_ShowerEat_BreakfastDrive_To_UniSit_1301_Lecture...etc...etc...etc...Drive_From_Uni...etc...etc...etc...
}
function Do_Week
{
Do_Monday
Do_Tuesday
Do_Wednesday
Do_Thursday
...etc...etc...etc...
}
28
04/10/2014
15
Components of an Algorithm
• Variables and values
• Instructions▫ Sequences
▫ Functions
▫ Selections
▫ Repetitions
Also required: Documentation
29
Struktur dasar algoritma
Struktur Urut (Sequence),
Struktur Pemilihan (Selection),
Struktur Pengulangan (Repetition).
30
04/10/2014
16
Sequence
• A series of instructions
• ...to be carried out one after the other...
• ...without hesitation or question
• Example:
▫ How to cook a Gourmet MealTM
31
Sequence -- Example
1. Open freezer door2. Take out Gourmet Meal™3. Close freezer door4. Open microwave door5. Put Gourmet Meal™ on carousel6. Shut microwave door7. Set microwave on high for 5 minutes8. Start microwave9. Wait 5 minutes10.Open microwave door11.Remove Gourmet Meal™12.Close microwave door
32
04/10/2014
17
Struktur Urut (Sequence)
• suatu struktur program dimana setiap baris program akan dikerjakan secara urut dari atas ke bawah sesuai dengan urutan penulisannya.
• instruksi baris program 2 akan dikerjakan jika instruksi baris program 1 telah selesai dikerjakan.
33
Selection
• An instruction that decides which of two possible sequences is executed
• The decision is based on a single true/falsecondition
• Examples:
▫ Car repair
▫ Reciprocals
34
04/10/2014
18
Selection Example – Car Repairif (motor turns) then {
CheckFuelCheckSparkPlugsCheckCarburettor
}else {
CheckDistributorCheckIgnitionCoil
}
35
Selection Example – Car Repair
if (motor turns) then {
CheckFuelCheckSparkPlugsCheckCarburettor
}else {
CheckDistributorCheckIgnitionCoil
}
36
Should be a true or falsecondition
04/10/2014
19
Selection Example – Car Repair
if (motor turns) then {
CheckFuelCheckSparkPlugsCheckCarburettor
}else {
CheckDistributorCheckIgnitionCoil
}
37
Sequence if the condition is true
Selection Example – Car Repair
if (motor turns) then {
CheckFuelCheckSparkPlugsCheckCarburettor
}else {
CheckDistributorCheckIgnitionCoil
}
38
Sequence if the condition is false
04/10/2014
20
Struktur Pemilihan (Selection),
• Menghasilkan nilai benar (true) atau nilai salah (false).
• IF sederhana IF <syarat> THEN
<instruksi>
• Pada bentuk IF sederhana ini,
intruksi akan dikerjakan jika
syarat yangdiuji benilai benar (true). Jika syarat yang diuji benilai salah (false) maka tidak ada instruksi yang dikerjakan.
39
IF … THEN … ELSE …• IF <syarat> THEN
<instruksi1>
ELSE
<instruksi2>
• Pada bentuk ini terdapat dua
kemungkinan pilihan yang
akan dikerjakan berdasarkan
hasil pengujian, jika syarat
yang diuji benilai benar maka instruksi1 yang dikerjakan, dan jika syarat yang diuji bernilai salah maka instruksi2 yang dikerjakan.
40
04/10/2014
21
IF Bersarang (Nested IF)
• IF <syarat1> THEN<instruksi1>
• ELSE IF <syarat2> THEN<instruksi2>
• ELSE IF <syarat3> THEN<instruksi3>
• ELSE IF <syaratm> THEN<instruksim>
• ELSE<Instruksin>
41
Repetition
• Repeat an instruction...
▫ ...while (or maybe until) some true or false condition occurs
▫ Test the condition each time beforerepeating the instruction
• Also known as iteration or loop• Example:
▫ Algorithm for getting a date
42
04/10/2014
22
Repetition – Example
function AskOnDate ( name, time, location ){
Phone(name)Say("Hey", name, "it's your lucky day!")Say("Wanna come to", location, "at", time, "?")ListenToReply ( )start begging count at zerowhile (reply is "No" and begging count < 100){
Say("Oh please!")add 1 to begging count ListenToReply ( )
}}
43
Repetition – Example (cont)
function AskOnDate ( name, time, location ){
Phone(name)Say("Hey", name, "it's your lucky day!")Say("Wanna come to", location, "at", time, "?")ListenToReply ( )start begging count at zerowhile ( reply is "No" and begging count < 100 ){
Say("Oh please!")add 1 to begging countListenToReply ( )
}}
44
Condition is tested before sequence
04/10/2014
23
Repetition – Example (cont)
function AskOnDate ( name, time, location ){
Phone(name)Say("Hey", name, "it's your lucky day!")Say("Wanna come to", location, "at", time, "?")ListenToReply ( )start begging count at zerowhile (reply is "No" and begging count < 100){
Say("Oh please!")add 1 to begging countListenToReply ( )
}}
45
Sequence may not get executed at all
Repetition – Example (cont)
function AskOnDate ( name, time, location ){
Phone(name)Say("Hey", name, "it's your lucky day!")Say("Wanna come to", location, "at", time, "?")ListenToReply ( )start begging count at zerowhile (reply is "No" and begging count < 100){
Say("Oh please!")add 1 to begging countListenToReply ( )
}}
46
Ensure initial values of variables used in the conditions are set correctly
04/10/2014
24
Repetition – Example (cont)
function AskOnDate ( name, time, location ){
Phone(name)Say("Hey", name, "it's your lucky day!")Say("Wanna come to", location, "at", time, "?")ListenToReply ( )start begging count at zerowhile (reply is "No" and begging count < 100){
Say("Oh please!")add 1 to begging countListenToReply ( )
}}
47
Ensure the variables used in the conditions are updated in each repetition
Repetition – Example (cont)
function AskOnDate ( name, time, location ){
Phone(name)Say("Hey", name, "it's your lucky day!")Say("Wanna come to", location, "at", time, "?")ListenToReply ( )start begging count at zerowhile (reply is "No" and begging count < 100){
Say("Oh please!")}
}
48
Infinite loop
• What if we don’t increment the begging count?
04/10/2014
25
Struktur pengulangan repetition
• Struktur for
• Mengulang satu baris instruksi atau satu blok instruksi sampai jumlah perulangan yang disyaratkan terpenuhi.
• Ciri utama terdapat nilai awal dan nilai akhir yang menunjukkan banyaknya pengulangan yang akan dilakukan.
49
Struktur while• untuk mengulang satu baris instruksi atau
satu blok baris instruksi selama syarat yang diberikan masih terpenuhi.
• Syarat akan diuji didepan.
• Jika syarat yang diuji bernilai benar maka instruksi1, instruksi2, instruksi3 akan dikerjakan, setelah mengerjakan instruksi1, instruksi2, instruksi3 maka syarat akan diuji lagi.
• pengulangan akan berhenti jika syarat yang diuji bernilai salah.
50
04/10/2014
26
Struktur do … while
• mengulang satu baris instruksi atau satu blok baris instruksi sampai syarat tidak terpenuhi.
• syarat akan diuji dibelakang, sehingga baris instruksi yang masuk dalam blok do…while minimal akan dikerjakan satu sekali.
51
Documentation
• Records what the algorithm does
• Describes how it does it
• Explains the purpose of each component of the algorithm
• Notes restrictions or expectations
• Example:▫ Getting a date (again)
52
04/10/2014
27
Documentation -- ExampleThink of something romantic to dodecide on time and location
Work through address book to look for a person
initialise booking to “unsuccessful”until (successfully booked){
get next Name in little black bookAskOnDate(Name, Time, Location)DetermineBookingSuccess
}
Assumes that I will find someone in the book before it runs out
SighWithRelief
53
From Algorithms to Programs
54
Problem
ProgramProgram
AlgorithmAlgorithm: A sequence of instructions describing how to do a task (or process)
04/10/2014
28
The Software Development Process
• Define the problem clearly
• Analyse the problem thoroughly
• Design an algorithm carefully
• Code the algorithm efficiently
• Test the code thoroughly
• Document the system lucidly
55
Top-down Algorithm Design
• Write down what you have to do
• Break that into 3-7 smaller steps
• Break each step into 3-7 smaller steps
• Keeping subdividing until each individual step is easy enough to do
• Example:▫ Learning
56
04/10/2014
29
Top-down Design -- Example
57
Learn
Prepare
Study
Reinforce
ReadMake notesPrepare questions
Attend lectureListen and thinkComplete pracAttend tute
Record answers to questions
Revise notes
Read lecture notesRead textbook
Read exerciseDesign algorithmCode solutionTest and document
Record insights
Cara Penyajian Algoritma
• Uraian Deskriptif▫ Menggunakan bahasa yang bisa di gunakan sehari-
hari
• Menggunakan flow chart (diagram alir)
• Menggunakan pseudo-code▫ Ditulis dalam kode-kode yang disepakati yang
mempunyai arti
58
04/10/2014
30
59
Algoritma dan Flowchart
• Algoritma merupakan urutan langkah logika pemikiran detail yang diperlukan untuk memecahkan masalah.
• Algoritma dapat direpresentasikan dalam format grafis yang disebut flowchart atau diagram alir.
• Flowchart juga dapat digunakan untuk menggambarkan aliran urutan program
60
04/10/2014
31
Bagan-bagan Flowchart
• Terminal▫ Bentuk : rounded rectangle
▫ Mengindikasikan titik awal atau akhir
61
Bagan-bagan Flowchart
• Connector▫ Bentuk : circle
▫ Mengindikasikan titik penghubung ke bagan lain yang terputus dalam satu halaman karena terlalu jauh atau memungkinkan memotong garis panah lain
62
04/10/2014
32
Bagan-bagan Flowchart
• Connector▫ Bentuk : pentagon
▫ Mengindikasikan titik penghubung ke bagan lain yang terputus karena beda halaman
63
Bagan-bagan Flowchart
• Preparation atau initialization▫ Bentuk : hexagon
▫ Mengindikasikan tahap awal pemrograman (misalnya mendeklarasikan variabel, mengidentifikasikan nilai awal konstanta atau variabel)
64
04/10/2014
33
Bagan-bagan Flowchart
• Data▫ Bentuk : parallelogram
▫ Mengindikasikan masukan atau keluaran data
65
Bagan-bagan Flowchart
• Process▫ Bentuk : rectangle
▫ Mengindikasikan proses komputasi
66
04/10/2014
34
Bagan-bagan Flowchart
• Predefined/Nested Process (Subroutine)▫ Bentuk : rectangle
▫ Mengindikasikan proses komputasi
67
Bagan-bagan Flowchart
• Manual Operation▫ Bentuk : trapezoid
▫ Mengindikasikan operasi yang dilakukan secara manual
68
04/10/2014
35
Bagan-bagan Flowchart
• Manual Input▫ Bentuk : trapezoid
▫ Mengindikasikan masukan manual menggunakan input device (misalnya keyboard, mouse, bar code reader, imaging device)
69
Bagan-bagan Flowchart
• Card▫ Bentuk : chamfered rectangle
▫ Mengindikasikan penggunaan card reader (misalnya punched card reader ataupun memory card reader)
70
04/10/2014
36
Bagan-bagan Flowchart
• Database atau Repository▫ Bentuk : drum
▫ Mengindikasikan penggunaan media penyimpanan basisdata
71
Bagan-bagan Flowchart
• Display▫ Bentuk : CRT Symbol
▫ Mengindikasikan proses penampilan informasi untuk dibaca atau dilihat user di layar monitor atau projector
72
04/10/2014
37
Bagan-bagan Flowchart
• Report▫ Bentuk : Sheet
▫ Mengindikasikan proses pencetakan laporan untuk dibaca atau dilihat user menggunakan printer atau plotter
73
Bagan-bagan Flowchart
• Annotation▫ Bentuk : Arrow
▫ Mengindikasikan hubungan presedensi antar operasi atau alur urutan operasi
74
04/10/2014
38
Bagan-bagan Flowchart
• Decision▫ Bentuk : diamond
▫ Mengindikasikan pencabangan alternatif operasi dengan pengambilan keputusan berdasarkan kriteria atau kondisi
75
Decision / Condition Structure
76
YES
NO
YES
NO
YES
NO
YES
NO
04/10/2014
39
Repetition / Recursive Structure
77
YES
NO
YES
NO
Metodologi Pengembangan Program
78
Mulai
Analisis Domain Masalah
Merumuskan Algoritma
SemuaSkenarioTertulis ?
Mapping Flowchart
StrukturLogika
Sesuai ?
Verify Program Code
Identifier,Syntax,
Semantic ?
Debug Listing Program
Compile Machine Code
CompileBerhasil
?
Eksekusi Program
EksekusiBerhasil
?
Keluaran Program Sesuai ?
Eksekusi Program
Selesai
04/10/2014
40
Contoh Algoritma
Step 1: Turn the stereo on.Step 2: If the band is set to FM, switch it to AM.Step 3: If the station is set to a station greater
than 610, turn the station to the left until 610 is reached.
Step 4: If the station is set to a station less than 610, turn the station to the right until 610 is reached.
Step 5: Listen to the best sports talk station in the country.
79
80
Contoh Flowchart
Top Related