Anda di halaman 1dari 83

ALGORITMA DAN

FLOWCHART
1 Pemrograman Komputer
Pertemuan 3
PROBLEM
2
PROBLEM
 Pertanyaan atau tugas yang kita cari jawaban
dan/atau penyelesaiannya

HOW DO WE SOLVE PROBLEMS?


Experience
Guesswork-
We "just do" (possibly
and-luck
someone else's)

Trial-and-error Scientifically"
3
THE PROBLEM-SOLVING PROCESS

Analysis
Problem specification
Design
Algorithm
Implementation
Program

Compilation
Executable (solution) 4
THE PROBLEM-SOLVING PROCESS
“Doctor, my head hurts“

Analysis
Patient has elevated pressure in
anterior parietal lobe
Problem specification

1. Sterilize cranial saw


Design 2. Anaesthetize patient
3. Remove top of skull
Algorithm 4. Get the big spoon...
5. etc., etc.
Implementation
sterilize(saw,alcohol);
raise_hammer();
Program
lower hammer(fast);
Compilation start(saw);
/* etc. etc. */
010011101011001010101010100101010101010011
5
Executable (solution) 001010101010100101101001110101010101001
001011101001111010101011111010101000110
100001101...
ALGORITMA
6
DEFINISI ALGORITMA
 Algoritmaadalah urutan langkah logis
tertentu untuk memecahkan suatu
masalah
 Urutan langkah logis, yang berarti algoritma harus
mengikuti suatu urutan tertentu, tidak boleh
melompat-lompat
 Alurpemikiran 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,
7
atau tabel tertentu
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.
8
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) 9
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
10
akal
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

11
ALMOND AND HONEY Preheat oven for 200° C
SLICE Line a 30 cm  20 cm baking
tray with baking paper,
1/2 quantity Shortcrust and then with pastry
Pastry Bake blind for 20 minutes,
185 g unsalted butter then remove weights and
100 g castor sugar foil
5 tablespoons honey Turn oven up to 220° C.
50 ml cream Bring remaining ingredients
50 ml brandy or any to a boil, stirring.
other liqueur or spirit Spread evenly over pastry.
300 g flaked almonds Bake until topping is
bubbling and has
caramelised evenly, about
From: Stephanie Alexander, The Cook’s
Companion, Viking/Penguin, Ringwood, 15 minutes.
Victoria, 1996, p. 349.
Cool before cutting into 12

fingers or squares.
ALMOND AND HONEY Preheat oven for 200° C
SLICE Line a 30 cm  20 cm baking
tray with baking paper,
1/2 quantity Shortcrust and then with pastry
Pastry Bake blind for 20 minutes,
185 g unsalted butter then remove weights and
100 gInstructions
castor sugarare given foil
5 tablespoons
in the order
honey
in which Turn oven up to 220° C.
50 mlthey are performed
cream Bring remaining ingredients
50 ml(“executed”)
brandy or any to a boil, stirring.
other liqueur or spirit Spread evenly over pastry.
300 g flaked almonds Bake until topping is
bubbling and has
caramelised evenly, about
From: Stephanie Alexander, The Cook’s
Companion, Viking/Penguin, Ringwood, 15 minutes.
Victoria, 1996, p. 349.
Cool before cutting into 13

fingers or squares.
CORRECT ALGORITHM?
Cut chicken into pieces Arrange chicken on rice,
and brown the pieces on cover casserole and
all sides in a casserole bake in a moderate
dish in hot olive oil. oven (350°F) for 20
Remove the chicken and to minutes or until the
the juices in the rice is tender.
casserole add garlic, Add beans and
onions and green artichokes during last
peppers, and sauté until 10 minutes of cooking.
onion is golden.
Add bay leaf, whole
tomatoes, and chicken
From: “Arroz Con Pollo” in The
broth. Margaret Fulton Cookbook,
14
When the broth boils add Hamlyn, Sydney, 1968.
salt, saffron and rice.
CORRECT ALGORITHM?
Cut chicken into pieces Arrange chicken on rice,
and brown the pieces on cover casserole and
all sides in a casserole bake in a moderate
dish in hot olive oil. oven (350°F) for 20
Remove the chicken and to minutes or until the
the juices in the rice is tender.
casserole add garlic, Add beans and
onions and green artichokes during last
peppers, and sauté until 10 minutes of cooking.
onion is golden.
Add bay leaf, whole
tomatoes, and chicken
From: “Arroz Con Pollo” in The
broth. Margaret Fulton Cookbook,
15
When the broth boils add Hamlyn, Sydney, 1968.
salt, saffron and rice.
CORRECT ALGORITHM?
Cut chicken into pieces Arrange chicken on rice,
and brown the pieces on cover casserole and
all sides in a casserole bake in a moderate
dish in hot olive oil. oven (350°F) for 10
minutes.
Remove the chicken and to
the juices in the Add beans and
artichokes.
casserole add garlic,
onions and green Cover, and bake for
peppers, and sauté until another 10 minutes or
onion is golden. until rice is tender.
Add bay leaf, whole
tomatoes, and chicken
broth.
16
When the broth boils add
salt, saffron and rice.
CORRECT ALGORITHM ???...

17
CORRECT ALGORITHM

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

19
ALMOND AND HONEY Preheat oven for 200° C
SLICE Line a 30 cm  20 cm baking
tray with baking paper,
1/2 quantity Shortcrust and then with pastry
Pastry
185 g unsalted butter Bake blind for 20 minutes,
then remove weights and
100 g castor sugar foil
5 tablespoons honey
Turn oven up to 220° C.
50 ml cream
Bring remaining ingredients
50 ml brandy or any
other liqueur or spirit to a boil, stirring.
300 g flaked almonds Spread evenly over pastry.
Bake until topping is
bubbling and has
caramelised evenly, about
From: Stephanie Alexander, The Cook’s
Companion, Viking/Penguin, Ringwood, 15 minutes.
Victoria, 1996, p. 349.
Cool before cutting into 20

fingers or squares.
ALMOND AND HONEY Preheat oven for 200° C
SLICE Line a 30 cm  20 cm baking
tray with baking paper,
1/2 quantity Shotcrust and then with pastry
Pastry Bake blind for 20 minutes,
185 g unsalted butter then remove weights and
100 g castor sugar foil
5 tablespoons honey Turn oven up to 220° C.
50 ml cream Bring remaining ingredients
50 ml brandy or any to a boil, stirring.
other liqueur or spirit Spread evenly over pastry.
300 g flaked almonds Bake until topping is
bubbling and has
caramelised evenly, about
From: Stephanie Alexander, The Cook’s
Companion, Viking/Penguin, Ringwood, 15 minutes.
Victoria, 1996, p. 349.
Cool before cutting into 21

fingers or squares.
VARIABLES
 Arecontainers for values – places to store
values
 Example:
Variable Values

This jar
10 cookies

can contain 50 grams of sugar


3 slices of cake
etc. 22
RESTRICTIONS ON VARIABLES
 Variables may be restricted to contain a specific
type of value

23
INSTRUCTIONS (PRIMITIVES)

Some action that is


 simple
 unambiguous
 that the system knows about...
 ...and should be able to actually do

24
INSTRUCTIONS – EXAMPLES
 Take off your shoes
 Count to 10

 Cut along dotted line

 Knit 1
Directions to perform
specific actions on values
 Purl 2
and variables
 Pull rip-cord firmly

 Sift 10 grams of arsenic

25
INSTRUCTIONS -- APPLICATION
 Some instructions can only be applied to a
specific type of values or variables
 Examples:

26
INSTRUCTIONS (PRIMITIVES) --
RECOMMENDATIONS
 When writing an algorithm, make each
instruction simple and unambiguous
 Example:

Cut chicken into pieces and Cut chicken into pieces.


brown the pieces on all Heat olive oil in a casserole
sides in a casserole dish dish.
in hot olive oil. Brown the chicken pieces in
the casserole dish. 27
INSTRUCTIONS (PRIMITIVES)
 When writing an algorithm, make each
A “sequence”
instruction of
simple and unambiguous
simple instructions
 Example:

Cut chicken into pieces and Cut chicken into pieces.


brown the pieces on all Heat olive oil in a casserole
sides in a casserole dish dish.
in hot olive oil. Brown the chicken pieces in
the casserole dish. 28
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

29
FUNCTION -- EXAMPLE
function Drive_To_Uni
{
1. find car keys ...etc...etc...etc...
2. disable car alarm 52. find parking space
3. open car door 53. pull into parking
4. get in car space
5. shut car door 54. turn off engine
6. put keys in ignition 55. remove keys from
7. start car ignition
56. open car door
8. back car out of
driveway 57. get out
9. drive to end of street 58. shut car door
10. turn right 59. lock car door
11. drive to end of street 60. enable alarm
}
12. turn left
30
...etc...etc...etc
FUNCTION – EXAMPLE

function Do_Wednesday function Do_Week


{ {
Wake_up Do_Monday
Have_Shower
Do_Tuesday
Eat_Breakfast
Drive_To_Uni Do_Wednesday
Sit_1301_Lecture Do_Thursday
...etc...etc...etc... ...etc...etc...etc...
Drive_From_Uni }
...etc...etc...etc...
} 31
COMPONENTS OF AN ALGORITHM
 Variables and values
 Instructions
 Sequences
 Functions
 Selections
 Repetitions
Also required: Documentation

32
STRUKTUR DASAR ALGORITMA

Struktur Urut
(Sequence),

Struktur Pemilihan
(Selection),

Struktur Pengulangan
(Repetition). 33
SEQUENCE
A series of instructions
 ...to be carried out one after the
other...
 ...without hesitation or question
 Example:

 How to cook a Gourmet


MealTM
34
SEQUENCE -- EXAMPLE
1. Open freezer door
2. Take out Gourmet Meal™
3. Close freezer door
4. Open microwave door
5. Put Gourmet Meal™ on carousel
6. Shut microwave door
7. Set microwave on high for 5 minutes
8. Start microwave
9. Wait 5 minutes
10. Open microwave door
11. Remove Gourmet Meal™
35
12. Close microwave door
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.

36
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

37
SELECTION EXAMPLE – CAR REPAIR
if (motor turns)
then
{
CheckFuel
CheckSparkPlugs
CheckCarburettor
}
else
{
CheckDistributor
CheckIgnitionCoil 38
}
SELECTION EXAMPLE – CAR REPAIR

if (motor turns)
then
{
Should be a
CheckFuel true or false
CheckSparkPlugs
CheckCarburettor
condition
}
else
{
CheckDistributor
CheckIgnitionCoil
} 39
SELECTION EXAMPLE – CAR REPAIR

if (motor turns)
then
{
CheckFuel
CheckSparkPlugs
Sequence if
CheckCarburettor the condition
} is true
else
{
CheckDistributor
CheckIgnitionCoil
} 40
SELECTION EXAMPLE – CAR REPAIR

if (motor turns)
then
{
CheckFuel
CheckSparkPlugs
CheckCarburettor Sequence if the
}
else condition is
{ false
CheckDistributor
CheckIgnitionCoil
} 41
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. 42
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 43

salah maka instruksi2 yang dikerjakan.


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> 44
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

45
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 zero
while (reply is "No" and begging count < 100)
{
Say("Oh please!")
add 1 to begging count
ListenToReply ( )
46
}
}
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 zero
while ( reply is "No" and begging count < 100 )
{
Say("Oh please!")
add 1 to begging count Condition is tested
ListenToReply ( ) before sequence
}
}
47
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 zero
while (reply is "No" and begging count < 100)
{
Say("Oh please!")
add 1 to begging count
Sequence may not
ListenToReply ( ) get executed at all
} 48

}
REPETITION – EXAMPLE (CONT)
function AskOnDate ( name, time, location )
{
Ensure initial
Phone(name) values of variables
Say("Hey", name, "it's your lucky day!")
used in the
Say("Wanna come to", location, "at", time, "?")
ListenToReply ( )
conditions are set
start begging count at zero correctly
while (reply is "No" and begging count < 100)
{
Say("Oh please!")
add 1 to begging count
ListenToReply ( )
}
} 49
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 zero
while (reply is "No" and begging count < 100)
{
Say("Oh please!")
add 1 to begging count Ensure the variables
ListenToReply ( ) used in the conditions
} are updated in each 50
} repetition
REPETITION – EXAMPLE (CONT)
• What if we don’t increment the begging count?
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 zero
while (reply is "No" and begging count < 100)
{
Say("Oh please!")
} Infinite loop 51

}
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.
52
53
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.
54
 pengulangan akan berhenti jika
syarat yang diuji bernilai salah.
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. 55
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)

56
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
AskOnDate(Name, Time, Location)
DetermineBookingSuccess
}

Assumes that I will find someone in the book


before it runs out
57
SighWithRelief
FROM ALGORITHMS TO PROGRAMS

Problem Algorithm: A sequence of


instructions describing how to do a
task (or process)

Program 58
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

59
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
60
TOP-DOWN DESIGN -- EXAMPLE
Read lecture notes
Read
Read textbook
Make notes
Prepare Prepare questions

Read exercise
Attend lecture
Design algorithm
Learn Listen and think
Study Complete prac
Code solution
Test and document
Attend tute
Record insights
Record answers to
Reinforce questions
Revise notes
61
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

62
FLOWCHART
63
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

64
BAGAN-BAGAN FLOWCHART
 Terminal
 Bentuk : rounded rectangle
 Mengindikasikan titik awal atau akhir

65
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

66
BAGAN-BAGAN FLOWCHART
 Connector
 Bentuk : pentagon
 Mengindikasikan titik penghubung ke bagan
lain yang terputus karena beda halaman

67
BAGAN-BAGAN FLOWCHART
 Preparation atau initialization
 Bentuk : hexagon
 Mengindikasikan tahap awal pemrograman
(misalnya mendeklarasikan variabel,
mengidentifikasikan nilai awal konstanta atau
variabel)

68
BAGAN-BAGAN FLOWCHART
 Data
 Bentuk : parallelogram
 Mengindikasikan masukan atau
keluaran data

69
BAGAN-BAGAN FLOWCHART
 Process
 Bentuk : rectangle
 Mengindikasikan proses komputasi

70
BAGAN-BAGAN FLOWCHART
 Predefined/Nested Process (Subroutine)
 Bentuk : rectangle
 Mengindikasikan proses komputasi

71
BAGAN-BAGAN FLOWCHART
 Manual Operation
 Bentuk : trapezoid
 Mengindikasikan operasi yang dilakukan
secara manual

72
BAGAN-BAGAN FLOWCHART
 Manual Input
 Bentuk : trapezoid
 Mengindikasikan masukan manual
menggunakan input device (misalnya
keyboard, mouse, bar code reader, imaging
device)

73
BAGAN-BAGAN FLOWCHART
 Card
 Bentuk : chamfered rectangle
 Mengindikasikan penggunaan card reader
(misalnya punched card reader ataupun
memory card reader)

74
BAGAN-BAGAN FLOWCHART
 Database atau Repository
 Bentuk : drum
 Mengindikasikan penggunaan media
penyimpanan basisdata

75
BAGAN-BAGAN FLOWCHART
 Display
 Bentuk : CRT Symbol
 Mengindikasikan proses penampilan informasi
untuk dibaca atau dilihat user di layar
monitor atau projector

76
BAGAN-BAGAN FLOWCHART
 Report
 Bentuk : Sheet
 Mengindikasikan proses pencetakan laporan
untuk dibaca atau dilihat user menggunakan
printer atau plotter

77
BAGAN-BAGAN FLOWCHART
 Annotation
 Bentuk : Arrow
 Mengindikasikan hubungan presedensi antar
operasi atau alur urutan operasi

78
BAGAN-BAGAN FLOWCHART
 Decision
 Bentuk : diamond
 Mengindikasikan pencabangan alternatif
operasi dengan pengambilan keputusan
berdasarkan kriteria atau kondisi

79
DECISION / CONDITION STRUCTURE

NO NO NO

YES YES YES


NO

YES

80
REPETITION / RECURSIVE STRUCTURE

YES

NO
NO

YES
81
METODOLOGI PENGEMBANGAN PROGRAM
Mulai Compile
Struktur Machine Code Keluaran
Logika Program
Sesuai ? Sesuai ?
Analisis Domain
Masalah
Compile
Berhasil
Merumuskan Verify ? Eksekusi
Algoritma Program Code Program

Debug Eksekusi
Semua Listing Program Program Selesai
Skenario
Tertulis ?

Identifier, Eksekusi
Syntax, Berhasil
Semantic ? ?
Mapping
Flowchart
82
TUGAS
 Buat algoritma:
 Menghitung volume tabung
 Menampilkan segitiga angka sampai angka ke - n
1
22
333
nn…..n (sebanyak n)
 Tampilkan algoritma di atas dalam bentuk
deskriptif dan flowchart
 Buat contoh running-nya

83

Anda mungkin juga menyukai