Pert 6: Algoritma Pemrograman 1
(Alpro1) 4 sks
By. Rita Wiryasaputra, ST., M. Cs.
ritasaputra@gmail.com
Latihan 1
1.
Tulislah sebuah program yang dapat menghitung luas bujursangkar.
Adapun rumus luas=sisi * sisi. Telah diketahui bahwa sisi = 5. Masukan :
tidak ada
Keluaran : hasil luas bujursangkar
Program Luas Bujur Sangkar
Luas Bujursangkar yang dihitung adalah …
2.
Tulislah sebuah program yang mendefinisikan sebuah konstanta yang
bernilai 25, lalu tuliskan nilai konstanta tersebut ke layar monitor.
Masukan : tidak ada
Keluaran : nilai konstanta
Program Konstanta
Latihan 1
3.
Tulislah sebuah program yang membaca sebuah nama bertipe string dari
keyboard, lalu menuliskan pesan tertentu.
Masukan : nama
Keluaran : pesan dengan nama yang dimasukkan
Program registrasi
Registrasi Praktikum Algoritma dan Pemrograman 1
{proses input}
Nama : XXXXX
{proses output, bersihkan layar terlebih dahulu}
Selamat pagi, XXXXX
Tugas 6
• Buatlah makalah tentang program impianku yang bermanfaat bagi banyak
orang. Konsep Portofolio. Dikumpulkan pada 11 November 2015 jam 08.00
UIGM
• Format cover seperti pengerjaan makalah tugas 2 dicetak di kertas
kambing warna merah dalam Ukuran kertas jenis A4, berukuran font 14 pt,
bentuk Calibri, dijilid spiral, penilaian (kreativitas, detil isi materi, tata
bahasa yang baik dan benar, kerapihan, ketepatan waktu)
Materi:
• Carilah program yang bermanfaat bagi banyak orang ,
• Capture/Screen shoot bentuk programnya
• Sebutkan karakteristik program tersebut, sudah berapa banyak program
sejenis??
• Menurutmu, mengapa program tersebut bermanfaat
• Sejauh informasi yang telah dilihat, dibaca maka sudah berapa banyakkah
pengguna yang menggunakan program tersebut??
• Bahasa pemrograman apakah yang dipergunakan untuk program tersebut.
• Ceritakan tentang Tindakan apa yang kamu lakukan untuk belajar
pemrograman??
Sejarah Bahasa C
• Bersumber dari bahasa BCPL (Martin Richards -1967) dan B (Ken
Thompson -1970)
• C diciptakan Dennis Ritchie dari Bell Laboratories pada tahun 1972 dan
diimplementasikan pada komputer DEC PDP-11
• Pada 1978 Dennis Ritchie dan Brian Kernighan kemudian
mempublikasikan buku The C Programming Language yang semakin
memperluas pemakaiannya dan dijadikan standar oleh ANSI (American
National Standard Institute) pada tahun 1989
• C kemudian dikembangkan lagi oleh Bjarne Stroustrup menjadi C++
(1986)
• C dan/atau C++
banyak digunakan
(sehingga menjadi
‘standar’) sebagai bahasa pemrograman untuk
Proses penerjemahan bahasa C
Editor Preprocessor Compiler Linker Loader DISK .c .h .obj .out (UNIX) .exe (MS)Program sederhana I [1]
• Contoh program untuk menampilkan sebaris teks
Selamat
menggunakan bahasa C!
pada layar:
1. /* Program pertama dalam bahasa C */ 2. #include <stdio.h>
3. #include <iostream.h>
4. // fungsi main mulai eksekusi program 5. void main ()
6. {
7. cout<<“Selamat menggunakan bahasa C!\n”;
8. getch(); /* indikasi program berakhir dengan sukses */ 9. } /* akhir fungsi main */
Program sederhana I [2]
Komentar diawali dengan tanda // atau diawali /* dan diakhiri dengan */ (seperti
terdapat pada baris-1,4,8,dan 9), komentar tidak dipedulikan/diproses oleh compiler. Bermanfaat untuk memudahkan pembacaan dan pemahaman sebuah program.
Baris dengan awalan # (seperti pada baris-2) diproses oleh preprocessor C++ sebelum
program dikompilasi. Baris tersebut menunjukkan bahwa preprocessor harus mengikutsertakan standard input/output header (stdio.h) pada program. Header ini mengandung informasi yang digunakan compiler untuk mengkompilasi pemanggilan fungsi standar input/output seperti cout (baris-7).
void main() merupakan fungsi utama program dan selalu merupakan bagian dari program dalam C++, karena berjalannya program/instruksi ditentukan oleh fungsi ini.
Tanda kurung kurawal buka { dan tutup } merupakan penanda body dari sebuah fungsi
atau sering disebut juga block fungsi/program.
cout<<“Selamat menggunakan bahasa C!\n“ ; menghasilkan aksi yaitu menampilkan teks“Selamat menggunakan bahasa C!”
1. /* Program pertama dalam bahasa C */ 2. #include <iostream.h>
3. // fungsi main mulai eksekusi program 4. void main( )
5. {
6. cout << “Selamat menggunakan bahasa C!\n“ ;
7. getch(); /* indikasi program berakhir dengan sukses */ 8. } /* akhir fungsi main */
Program sederhana I [3]
komentar preprocessor main function statement function bodyKonsep Memori [1]
• Variabel
– Nama-nama variabel berkaitan dengan lokasi-lokasi di memori
komputer
– Setiap variabel memiliki sebuah nama, sebuah tipe, sebuah ukuran
dan sebuah nilai
– Ketika sebuah nilai baru diberikan pada sebuah variabel (misalnya
melalui cin) maka nilai yang lama akan diganti (dan hilang)
– Membaca variabel dari memori tidak akan mengubah nilainya
• Representasi visual:
Konsep Memori [2]
integer1
45
integer2
72
integer1
45
integer2
72
sum
117
Aritmatika [1]
• Perhitungan Aritmatika
– Gunakan * untuk perkalian dan / untuk pembagian – Pembagian bilangan bulat membuang sisa pembagian
• 7 / 5 dievaluasi menjadi 1
– Operator Modulus (%) menghasilkan sisa pembagian • 7 % 5 dievaluasi menjadi 2
• Operator precedence
– Beberapa operator aritmatika lebih diprioritaskan (dihitung lebih dahulu) dibandingkan operator lainnya (misalkan perkalian dan pembagian
didahulukan dibandingkan penjumlahan dan pengurangan) • Gunakan tanda kurung jika diperlukan
– Contoh: Hitung nilai rata-rata dari variabel-variabel a, b and c • Jangan gunakan: a + b + c / 3
C operation Arithmetic operator Algebraic expression C expression Addition + f + 7 f + 7 Subtraction - p – c p - c Multiplication * bm b * m Division / x / y x / y Modulus % r mod s r % s
Aritmatika [2]
• Operator-operator aritmatika:
Aturan precedence operator:
Operator(s) Operation(s) Order of evaluation (precedence)
() Parentheses Evaluated first. If the parentheses are nested, the expression in the innermost pair is
evaluated first. If there are several pairs of parentheses “on the same level” (i.e., not nested), they are evaluated left to right.
*, /, or % Multiplication,Division,
Modulus
Evaluated second. If there are several, they are evaluated left to right.
+ or - Addition Subtraction
Evaluated last. If there are several, they are evaluated left to right.
Aritmatika [3]
St ep 1. y = 2 * 5 * 5 + 3 * 5 + 7; St ep 2. y = 10 * 5 + 3 * 5 + 7; St ep 3. y = 50 + 3 * 5 + 7; St ep 4. y = 50 + 15 + 7; St ep 5. y = 65 + 7; 2 * 5 is 10 10 * 5 is 50 3 * 5 is 15 50 + 15 is 65 65 + 7 is 72(Left m ost mult ip lic at ion)
(Left m ost mult ip lic at ion)
(Mult ip lic at ion bef ore ad dition)
(Left m ost ad dit ion)
Pengambilan Keputusan: Persamaan dan
Operator Relasional [1]
• Eksekusi statement
– Menghasilkan aksi-aksi (penghitungan, input/output data) – Menghasilkan keputusan
• Ingin menampilkan “lulus" or “gagal" berdasarkan suatu syarat nilai tertentu
• if control statement
– Versi sederhana dahulu, lebih detail kemudian
– Jika suatu kondisi true, maka body statement if dieksekusi • 0 adalah false, non-zero adalah true
– Kontrol terhadap perintah selanjutnya setelah struktur if • Keywords
– Kata-kata khusus yang digunakan oleh bahasa C++
Pengambilan Keputusan: Persamaan dan
Operator Relasional [2]
Standard algebraic equality operator or relational operator
C equality or relational operator Example of C condition Meaning of C condition Equality Operators = == x == y x is equal to y != x != y x is not equal to y Relational Operators > > x > y x is greater than y < < x < y x is less than y
>= >= x >= y x is greater than or equal to y <= <= x <= y x is less than or equal to y
1 /* Fig. 2.13: fig02_13.c
2 Using if statements, relational
3 operators, and equality operators */
4 #include<stdio.h>
5 #include<conio.h>
6 #include<iostream.h>
7 int num1, /* first number to be read from user */
8 int num2; /* second number to be read from user */
9 void main()
10 {
11
12 cout <<"Enter two integers, and I will tell you\n";
13 cout <<"the relationships they satisfy: " ;
14 cin>>num1; /* read two integers */
15 cin>>num2; /* read two integers */
16
17 if ( num1 == num2 ) {
18 cout<<num1; cout<<”is equal to ", num2 ;
19 } /* end if */
20
21 if ( num1 != num2 ) {
22 cout<<num1; cout<<”is not equal to ", num2 ;
23 } /* end if */
25 if ( num1 < num2 ) {
26 cout<<num1; cout<<”is less than ", num2 ;
27 } /* end if */
28
29 if ( num1 > num2 ) {
30 cout<<num1; cout<<” greater than “ , num2 ;
31 } /* end if */
32
33 if ( num1 <= num2 ) {
34 cout<<num1; cout<<”is less than or equal to ", num2 ;
35 } /* end if */
36
37 if ( num1 >= num2 ) {
38 cout<<num1; cout<<”is greater than or equal to ", num2 ;
39 } /* end if */
40
41 getch(); /* indicate that program ended successfully */
42
43 } /* end function main */
Enter two integers, and I will tell you the relationships they satisfy: 3 7
3 is not equal to 7 3 is less than 7
3 is less than or equal to 7
Enter two integers, and I will tell you the relationships they satisfy: 22 12 22 is not equal to 12
22 is greater than 12
22 is greater than or equal to 12
Enter two integers, and I will tell you the relationships they satisfy: 7 7
7 is equal to 7
7 is less than or equal to 7 7 is greater than or equal to 7
Program Output (lanjutan)
Pengambilan Keputusan: Persamaan dan
Operator Relasional [3]
Operators Associativity * / % left to right + - left to right < <= > >= left to right == != left to right = right to leftPengambilan Keputusan: Persamaan dan
Operator Relasional [4]
Keywords
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
Algoritma dan Pseudocode
• Algoritma: urutan langkah-langkah yang dapat digunakan
untuk memecahkan suatu masalah
• Pseudocode:
– Bahasa buatan yang bersifat informal yang dapat membantu
untuk mengembangkan algoritma
– Serupa dengan bahasa sehari-hari
– Membantu mempermudah penulisan program; dengan
menggunakan statement-statement yang dapat dieksekusi,
mempermudah konversi ke bahasa pemrograman
Struktur Kontrol
• Semua program ditulis dalam 3 macam bentuk struktur kontrol:
– Sequence atau berturutan: struktur ini tersedia secara built-in. Secara default program dieksekusi secara berturutan sesuai urutan perintah
– Selection atau pilihan: ada 3 macam dalam bahasa C++: if, if…else, dan switch
– Repetition atau pengulangan: ada 3 macam dalam bahasa C++: while, do…while, dan for
• Flowchart
– Representasi grafis dari algoritma
– Menggunakan simbol-simbol khusus yang dihubungkan dengan garis beranak panah
– Simbol kotak melambangkan aksi
– Simbol oval melambangkan awal dan akhir suatu program atau blok program – Simbol berlian melambangkan keputusan/pilihan
Selection Control [1] (if)
• Statement if:
– Digunakan untuk seleksi suatu kondisi – Contoh pseudocode:
If student’s grade is greater than or equal to 60 Print “Passed”
– Contoh Flowchart:
true
Selection Control [2] (if)
– Jika kondisi true
• Statement Print dieksekusi dan program dilanjutkan ke statement berikutnya
– Jika kondisi false
• Statement Print diabaikan dan program dilanjutkan ke statement berikutnya
– Dalam bahasa C++:
if ( grade >= 60 )
Selection Control [3] (if…else)
• Statement if…else:
– Menspesifikasikan aksi baik untuk kondisi true maupun untuk kondisi false – Contoh pseudocode:
If student’s grade is greater than or equal to 60 Print “Passed” else Print “Failed” – Contoh Flowchart: true false
print “Failed” print “Passed”
Selection Control [4] (if…else)
• Dalam C++ : if ( grade >= 60 ) cout<< "Passed\n”; else cout<< "Failed\n”; • Ternary conditional operator (?:)– Memerlukan tiga argumen (kondisi, nilai jika true, nilai jika false) – Contoh di atas dapat ditulis sbb:
Cout<< “\n", grade >= 60 ? "Passed" : "Failed“ ; – Atau dapat ditulis sbb:
Selection Control [5] (if…else)
• Statement if…else bertingkat/bersarang:
– Digunakan untuk menguji banyak kondisi dimana menempatkan statement seleksi if…else di dalam statement if…else
– Sekali kondisi terpenuhi, sisa statement lainnya dilewatkan/diabaikan – Contoh pseudocode:
If student’s grade is greater than or equal to 90 Print “A”
else
If student’s grade is greater than or equal to 80 Print “B”
else
If student’s grade is greater than or equal to 70 Print “C”
else
If student’s grade is greater than or equal to 60 Print “D”
else
Selection Control [6] (if…else)
• Compound statement
– Ada lebih dari satu statement/aksi yang harus dieksekusi setelah suatu kondisi dipenuhi
– Sering disebut juga blok karena ditandai dengan pasangan { dan } – Contoh:
if ( grade >= 60 )
cout<< "Passed.\n“ ; else {
cout<< "Failed.\n“ ;
cout<< "You must take this course again.\n“ ;
}
– Tanpa tanda kurung kurawal, statement
cout<< "You must take this course again.\n“ ;
Selection Control [7] (switch)
• Multiple-Selection Statement switch:
– Berguna pada waktu sebuah variabel atau ekspresi diuji terhadap semua nilai yang mungkin dan masing-masing mengambil aksi yang berbeda
– Format penulisan:
• Sederetan label case dan opsional default case switch ( value ){ case '1': actions case '2': actions default: actions }
Selection Control [8] (switch)
– Flowchart statement switch:
true
false .
. .
case a case a action(s) break
case b case b action(s) break
false
false
case z case z action(s) break
true
true
Repetition Control: [1](FOR)
• Beberapa instruksi diulang untuk suatu jumlah
pengulangan tertentu. Jumlah pengulangan
dapat diketahui sebelumnya atau ditentukan
dalam pengulangan program.
For variabel := nilai awal DOWNTO nilai akhir DO {
………
For variabel := nilai awal To nilai akhir Do {
……… aksi
………
Repetition Control [1] (while)
• Struktur pengulangan structure
– Programmer menentukan aksi yang akan diulang selama kondisi tetap true – Psuedocode:
While there are more items on my shopping list Purchase next item and cross it off my list
– while loop diulang hingga kondisi menjadi false • Contoh:
int product = 2;
while ( product <= 1000 )
Repetition Control [2] (while)
product <= 1000 true product = 2 * product
false
Repetition Control [3] (while)
• Pengulangan yang dikontrol sebuah counter
– Loop diulang hingga counter mencapai angka tertentu
– Disebut juga definite repetition karena jumlah pengulangan dapat kita ketahui – Contoh: Sebuah kelas dengan 10 orang mahasiswa mengikuti kuis. Nilai kuis
adalah bilangan bulat dari 0 hingga 100. Tentukan nilai rata-rata kuis tersebut. – Pseudocode:
Set total to zero
Set grade counter to one
While grade counter is less than or equal to ten Input the next grade
Add the grade into the total Add one to the grade counter
Set the class average to the total divided by ten Print the class average
1 /* Fig. 3.6: fig03_06.c
2 Class average program with counter-controlled repetition */
3 #include <stdio.h>
4
5 /* function main begins program execution */
6 int main()
7 {
8 int counter; /* number of grade to be entered next */
9 int grade; /* grade value */
10 int total; /* sum of grades input by user */
11 int average; /* average of grades */
12
13 /* initialization phase */
14 total = 0; /* initialize total */
15 counter = 1; /* initialize loop counter */
16
17 /* processing phase */
18 while ( counter <= 10 ) { /* loop 10 times */
19 printf( "Enter grade: " ); /* prompt for input */
20 scanf( "%d", &grade ); /* read grade from user */
21 total = total + grade; /* add grade to total */
22 counter = counter + 1; /* increment counter */
23 } /* end while */
Enter grade: 98 Enter grade: 76 Enter grade: 71 Enter grade: 87 Enter grade: 83 Enter grade: 90 Enter grade: 57 Enter grade: 79 Enter grade: 82 Enter grade: 94 Class average is 81 25 /* termination phase */
26 average = total / 10; /* integer division */
27
28 /* display result */
29 printf( "Class average is %d\n", average );
30
31 return 0; /* indicate program ended successfully */
32
Repetition Control [4] (while)
• Pengulangan yang dikontrol sebuah sentinel
– Sentinel: tanda berhenti untuk keluar dari suatu loop, biasanya berupa
karakter, angka, atau tombol di keyboard sebagai tanda. Misalnya ‘Q’ untuk
exit.
– Loop diulang hingga mencapai sentinel tersebut
1 /* Fig. 3.8: fig03_08.c
2 Class average program with sentinel-controlled repetition */
3 #include <stdio.h>
4
5 /* function main begins program execution */
6 int main()
7 {
8 int counter; /* number of grades entered */
9 int grade; /* grade value */
10 int total; /* sum of grades */
11
12 float average; /* number with decimal point for average */
13
14 /* initialization phase */
15 total = 0; /* initialize total */
16 counter = 0; /* initialize loop counter */
17
18 /* processing phase */
19 /* get first grade from user */
20 printf( "Enter grade, -1 to end: " ); /* prompt for input */
21 scanf( "%d", &grade ); /* read grade from user */
22
23 /* loop while sentinel value not yet read from user */
24 while ( grade != -1 ) {
25 total = total + grade; /* add grade to total */
26 counter = counter + 1; /* increment counter */
28 printf( "Enter grade, -1 to end: " ); /* prompt for input */
29 scanf("%d", &grade); /* read next grade */
30 } /* end while */
31
32 /* termination phase */
33 /* if user entered at least one grade */
34 if ( counter != 0 ) {
35
36 /* calculate average of all grades entered */
37 average = ( float ) total / counter;
38
39 /* display average with two digits of precision */
40 printf( "Class average is %.2f\n", average );
41 } /* end if */
42 else { /* if no grades were entered, output message */
43 printf( "No grades were entered\n" );
44 } /* end else */
45
46 return 0; /* indicate program ended successfully */
47
Enter grade, -1 to end: 75 Enter grade, -1 to end: 94 Enter grade, -1 to end: 97 Enter grade, -1 to end: 88 Enter grade, -1 to end: 70 Enter grade, -1 to end: 64 Enter grade, -1 to end: 83 Enter grade, -1 to end: 89 Enter grade, -1 to end: -1 Class average is 82.50 Enter grade, -1 to end: -1 No grades were entered
Latihan 2
1. Tulislah sebuah program kuadrat bilangan 1 hingga bilangan tertentu
Masukan : bilangan (diasumsikan bilangan 4)
Keluaran : kuadrat bilangan 1 hingga kuadrat bilangan 4 Program Kuadrat Bilangan
Masukkan bilangan = ?
Kuadrat Bilangan adalah 1-1; 2-4; 3-9; 4-16;
2. Buatlah program yang dapat menampilkan formasi berikut :
1 1 2 1 2 3 1 2 3 4 1 2 3 1 2