Algoritma dan Pemrograman Lesson 2 Problem 1122022 Algoritma
Algoritma dan Pemrograman Lesson 2
Problem 1/12/2022 Algoritma dan Pemrograman - Genap 2012 2
Problem �Pertanyaan atau tugas yang kita cari jawaban dan/atau penyelesaiannya 1/12/2022 Algoritma dan Pemrograman - Genap 2012 3
How do we solve problems? �We "just do" �Guesswork-and-luck �Trial-and-error �Experience (possibly someone else's) �"Scientifically" 1/12/2022 Algoritma dan Pemrograman - Genap 2012 4
The Problem-solving Process 1/12/2022 Algoritma dan Pemrograman - Genap 2012 5
The Problem-solving Process � Problem � “Doctor, my head hurts" � Problem specification � Patient has elevated pressure in anterior parietal lobe � Algorithm � � � 1. Sterilize cranial saw 2. Anaesthetize patient 3. Remove top of skull 4. Get the big spoon. . . 5. etc. , etc. � Program � � � sterilize(saw, alcohol); raise_hammer(); lower hammer(fast); start(saw); /* etc. */ � Executable � 010011101011001010101010100101101001110101001001011101 0011110101111101000110100001101. . . 1/12/2022 Algoritma dan Pemrograman - Genap 2012 6
Algoritma 1/12/2022 Algoritma dan Pemrograman - Genap 2012 7
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 1/12/2022 Algoritma dan Pemrograman - Genap 2012 8
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. 1/12/2022 Algoritma dan Pemrograman - Genap 2012 9
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) 1/12/2022 Algoritma dan Pemrograman - Genap 2012 10
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 1/12/2022 Algoritma dan Pemrograman - Genap 2012 11
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 1/12/2022 Algoritma dan Pemrograman - Genap 2012 12
Almond and Honey Slice Ingredients Recipe � 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. From: Stephanie Alexander, The Cook’s Companion, Viking/Penguin, Ringwood, Victoria, 1996, p. 349. 1/12/2022 Algoritma dan Pemrograman - Genap 2012 13
Almond and Honey Slice Ingredients Recipe � 1/2 Instructions quantity Shortcrust Pastry are given � 185 ing the unsalted orderbutter in which are performed � 100 they g castor sugar (“executed”) � 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. From: Stephanie Alexander, The Cook’s Companion, Viking/Penguin, Ringwood, Victoria, 1996, p. 349. 1/12/2022 Algoritma dan Pemrograman - Genap 2012 14
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. 1/12/2022 �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. From: “Arroz Con Pollo” in The Margaret Fulton Cookbook, Hamlyn, Sydney, 1968. Algoritma dan Pemrograman - Genap 2012 15
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. 1/12/2022 �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. From: “Arroz Con Pollo” in The Margaret Fulton Cookbook, Hamlyn, Sydney, 1968. Algoritma dan Pemrograman - Genap 2012 16
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. 1/12/2022 �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. Algoritma dan Pemrograman - Genap 2012 17
Components of an Algorithm �Variables and values �Instructions �Sequences �Functions �Selections �Repetitions �Also required: Documentation 1/12/2022 Algoritma dan Pemrograman - Genap 2012 18
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 1/12/2022 Algoritma dan Pemrograman - Genap 2012 19
Almond and Honey Slice Ingredients Recipe � 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. From: Stephanie Alexander, The Cook’s Companion, Viking/Penguin, Ringwood, Victoria, 1996, p. 349. 1/12/2022 Algoritma dan Pemrograman - Genap 2012 20
Almond and Honey Slice Ingredients Recipe � 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. From: Stephanie Alexander, The Cook’s Companion, Viking/Penguin, Ringwood, Victoria, 1996, p. 349. 1/12/2022 Algoritma dan Pemrograman - Genap 2012 21
Variables �Are containers for values – places to store values � Example: Variable Values This jar 10 cookies can contain 50 grams of sugar 3 slices of cake etc. 1/12/2022 Algoritma dan Pemrograman - Genap 2012 22
Restrictions on Variables �Variables may be restricted to contain a specific type of value 1/12/2022 Algoritma dan Pemrograman - Genap 2012 23
Variables �A variable is an abstraction of a memory cell �Variables characterized by attributes �Type: to design, must consider scope, lifetime, type checking, initialization, and type compatibility �Design issues for names: �Maximum length? �Are connector characters allowed? �Are names case sensitive? �Are special words reserved words or keywords? 1/12/2022 Algoritma dan Pemrograman - Genap 2012 24
Variables Attributes �Name - not all variables have them �Address - the memory address with which it is associated �A variable may have different addresses at different times during execution �A variable may have different addresses at different places in a program �If two variable names can be used to access the same memory location, they are called aliases �Aliases are created via pointers, reference variables �Aliases are harmful to readability (program readers must remember all of them) 1/12/2022 Algoritma dan Pemrograman - Genap 2012 25
Variables Attributes �Type - determines the range of values of variables and the set of operations that are defined for values of that type; in the case of floating point, type also determines the precision �Value - the contents of the location with which the variable is associated �Abstract memory cell - the physical cell or collection of cells associated with a variable 1/12/2022 Algoritma dan Pemrograman - Genap 2012 26
Variables Types: Integer �Almost always an exact reflection of the hardware so the mapping is trivial �There may be as many as eight different integer types in a language �Sometimes support integer sizes: byte, short, int, long 1/12/2022 Algoritma dan Pemrograman - Genap 2012 27
Variables Types: Floating Point �Model real numbers, but only as approximations �Languages for scientific use support at least two floating-point types (e. g. , single and double; sometimes more) �Usually exactly like the hardware, but not always 1/12/2022 Algoritma dan Pemrograman - Genap 2012 28
Variables Types: Boolean �Simplest of all �Range of values: two elements, one for “true” and one for “false” �Could be implemented as bits, but often as bytes �Advantage: readability 1/12/2022 Algoritma dan Pemrograman - Genap 2012 29
Variables Types: Character �Stored as numeric codings �Most commonly used coding: ASCII �An alternative, 16 -bit coding: Unicode �Includes characters from most natural languages 1/12/2022 Algoritma dan Pemrograman - Genap 2012 30
Variables Types : String �Values are sequences of characters �Design issues: �Is it a primitive type or just a special kind of array? �Should the length of strings be static or dynamic? 1/12/2022 Algoritma dan Pemrograman - Genap 2012 31
Variables Type Checking �Generalize the concept of operands and operators to include subprograms and assignments �Type checking is the activity of ensuring that the operands of an operator are of compatible types �A compatible type is one that is either legal for the operator, or is allowed under language rules to be implicitly converted, by compiler- generated code, to a legal type �This automatic conversion is called a coercion. �A type error is the application of an operator to an operand of an inappropriate type 1/12/2022 Algoritma dan Pemrograman - Genap 2012 32
Variables Array Types �An array is an aggregate of homogeneous data elements in which an individual element is identified by its position in the aggregate, relative to the first element. 1/12/2022 Algoritma dan Pemrograman - Genap 2012 33
Variables Array Issues �What types are legal for subscripts? �Are subscripting expressions in element references range checked? �When are subscript ranges bound? �When does allocation take place? �What is the maximum number of subscripts? �Can array objects be initialized? �Are any kind of slices allowed? 1/12/2022 Algoritma dan Pemrograman - Genap 2012 34
Variables Array Indexing �Indexing (or subscripting) is a mapping from indices to elements �Index Syntax 1/12/2022 Algoritma dan Pemrograman - Genap 2012 35
Variables Record Types �A record is a possibly heterogeneous aggregate of data elements in which the individual elements are identified by names �Design issues: �What is the syntactic form of references to the field? �Are elliptical references allowed 1/12/2022 Algoritma dan Pemrograman - Genap 2012 36
Instructions (Primitives) �Some action that is �simple �unambiguous �that the system knows about. . . �. . . and should be able to actually do 1/12/2022 Algoritma dan Pemrograman - Genap 2012 37
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 1/12/2022 Directions to perform specific actions on values and variables Algoritma dan Pemrograman - Genap 2012 38
Instructions -- Application �Some instructions can only be applied to a specific type of values or variables �Examples: 1/12/2022 Algoritma dan Pemrograman - Genap 2012 39
Instructions (Primitives) -Recommendations �When writing an algorithm, make each instruction simple and unambiguous �Example: Cut chicken into pieces and Cut chicken into pieces. Heat olive oil in a casserole brown the pieces on all dish. sides in a casserole dish Brown the chicken pieces in in hot olive oil. the casserole dish. 1/12/2022 Algoritma dan Pemrograman - Genap 2012 40
Instructions (Primitives) A “sequence” of make each instruction �When writing an algorithm, instructions simple and unambiguous �Example: Cut chicken into pieces and Cut chicken into pieces. Heat olive oil in a casserole brown the pieces on all dish. sides in a casserole dish Brown the chicken pieces in in hot olive oil. the casserole dish. 1/12/2022 Algoritma dan Pemrograman - Genap 2012 41
Expression �Expressions are the fundamental means of specifying computations in a programming language �Expressions consist of operators, operands, parentheses, and function calls �To understand expression evaluation, need to be familiar with the orders of operator and operand evaluation �Essence of imperative languages is dominant role of assignment statements 1/12/2022 Algoritma dan Pemrograman - Genap 2012 42
Sequence �A series of instructions �. . . to be carried out one after the other. . . �. . . without hesitation or question �Example: �How to cook a Gourmet Meal. TM 1/12/2022 Algoritma dan Pemrograman - Genap 2012 43
Sequence -- Example 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 1/12/2022 Open freezer door Take out Gourmet Meal™ Close freezer door Open microwave door Put Gourmet Meal™ on carousel Shut microwave door Set microwave on high for 5 minutes Start microwave Wait 5 minutes Open microwave door Remove Gourmet Meal™ Close microwave door Algoritma dan Pemrograman - Genap 2012 44
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 1/12/2022 Algoritma dan Pemrograman - Genap 2012 45
Function -- Example function Drive_To_Uni { 1. find car keys 2. disable car alarm 3. open car door 4. get in car 5. shut car door 6. put keys in ignition 7. start car 8. back car out of driveway 9. drive to end of street 10. turn right 11. drive to end of street 12. turn left. . . etc… 1/12/2022 . . . etc. . . 52. find parking space 53. pull into parking space 54. turn off engine 55. remove keys from ignition 56. open car door 57. get out 58. shut car door 59. lock car door 60. enable alarm } Algoritma dan Pemrograman - Genap 2012 46
Function – Example function Do_Wednesday { Wake_up Have_Shower Eat_Breakfast Drive_To_Uni Sit_1301_Lecture. . . etc. . . Drive_From_Uni. . . etc. . . } 1/12/2022 function Do_Week { Do_Monday Do_Tuesday Do_Wednesday Do_Thursday. . . etc. . . } Algoritma dan Pemrograman - Genap 2012 47
Selection �An instruction that decides which of two possible sequences is executed �The decision is based on a single true/false condition �Examples: �Car repair �Reciprocals 1/12/2022 Algoritma dan Pemrograman - Genap 2012 48
Selection Example – Car Repair if (motor turns) then { Check. Fuel Check. Spark. Plugs Check. Carburettor } else { Check. Distributor Check. Ignition. Coil } 1/12/2022 Algoritma dan Pemrograman - Genap 2012 49
Selection Example – Car Repair if (motor turns) then { Check. Fuel Check. Spark. Plugs Check. Carburettor } else { Check. Distributor Check. Ignition. Coil } 1/12/2022 Should be a true or false condition Algoritma dan Pemrograman - Genap 2012 50
Selection Example – Car Repair if (motor turns) then { Check. Fuel Check. Spark. Plugs Check. Carburettor } else { Check. Distributor Check. Ignition. Coil } 1/12/2022 Algoritma dan Pemrograman - Genap 2012 Sequence if the condition is true 51
Selection Example – Car Repair if (motor turns) then { Check. Fuel Check. Spark. Plugs Check. Carburettor } else { Check. Distributor Check. Ignition. Coil } 1/12/2022 Algoritma dan Pemrograman - Genap 2012 Sequence if the condition is false 52
Repetition �Repeat an instruction. . . �. . . while (or maybe until) some true or false condition occurs �Test the condition each time before repeating the instruction �Also known as iteration or loop �Example: �Algorithm for getting a date 1/12/2022 Algoritma dan Pemrograman - Genap 2012 53
Repetition – Example function Ask. On. Date ( name, time, location ) { Phone(name) Say("Hey", name, "it's your lucky day!") Say("Wanna come to", location, "at", time, "? ") Listen. To. Reply ( ) start begging count at zero while (reply is "No" and begging count < 100) { Say("Oh please!") add 1 to begging count Listen. To. Reply ( ) } } 1/12/2022 Algoritma dan Pemrograman - Genap 2012 54
Repetition – Example (cont) function Ask. On. Date ( name, time, location ) { Phone(name) Say("Hey", name, "it's your lucky day!") Say("Wanna come to", location, "at", time, "? ") Listen. To. Reply ( ) start begging count at zero while ( reply is "No" and begging count < 100 ) { Say("Oh please!") add 1 to begging count Condition is tested Listen. To. Reply ( ) before sequence } } 1/12/2022 Algoritma dan Pemrograman - Genap 2012 55
Repetition – Example (cont) function Ask. On. Date ( name, time, location ) { Phone(name) Say("Hey", name, "it's your lucky day!") Say("Wanna come to", location, "at", time, "? ") Listen. To. Reply ( ) start begging count at zero while (reply is "No" and begging count < 100) { Say("Oh please!") Sequence may not add 1 to begging count get executed at all Listen. To. Reply ( ) } } 1/12/2022 Algoritma dan Pemrograman - Genap 2012 56
Repetition – Example (cont) function Ask. On. Date ( name, time, location ) Ensure initial { values of variables Phone(name) Say("Hey", name, "it's your lucky day!") used in the Say("Wanna come to", location, "at", time, "? ") conditions are set Listen. To. Reply ( ) start begging count at zero correctly while (reply is "No" and begging count < 100) { Say("Oh please!") add 1 to begging count Listen. To. Reply ( ) } } 1/12/2022 Algoritma dan Pemrograman - Genap 2012 57
Repetition – Example (cont) function Ask. On. Date ( name, time, location ) { Phone(name) Say("Hey", name, "it's your lucky day!") Say("Wanna come to", location, "at", time, "? ") Listen. To. Reply ( ) start begging count at zero while (reply is "No" and begging count < 100) { Say("Oh please!") add 1 to begging count Ensure the variables Listen. To. Reply ( ) used in the conditions } are updated in each } repetition 1/12/2022 Algoritma dan Pemrograman - Genap 2012 58
Repetition – Example (cont) • What if we don’t increment the begging count? function Ask. On. Date ( name, time, location ) { Phone(name) Say("Hey", name, "it's your lucky day!") Say("Wanna come to", location, "at", time, "? ") Listen. To. Reply ( ) start begging count at zero while (reply is "No" and begging count < 100) { Say("Oh please!") Infinite loop } } 1/12/2022 Algoritma dan Pemrograman - Genap 2012 59
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) 1/12/2022 Algoritma dan Pemrograman - Genap 2012 60
Documentation -- Example Think of something romantic to do decide 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 book Ask. On. Date(Name, Time, Location) Determine. Booking. Success } Assumes that I will find someone in the book before it runs out Sigh. With. Relief 1/12/2022 Algoritma dan Pemrograman - Genap 2012 61
From Algorithms to Programs 1/12/2022 Algoritma dan Pemrograman - Genap 2012 62
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 1/12/2022 Algoritma dan Pemrograman - Genap 2012 63
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 1/12/2022 Algoritma dan Pemrograman - Genap 2012 64
Top-down Design -- Example 1/12/2022 Algoritma dan Pemrograman - Genap 2012 65
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 1/12/2022 Algoritma dan Pemrograman - Genap 2012 66
SEE YOU…… 1/12/2022 Algoritma dan Pemrograman - Genap 2012 67
- Slides: 67