Upload
kharis-theo
View
226
Download
0
Embed Size (px)
Citation preview
7/27/2019 Pemrograman1 3 Expressions Forloops
1/47
Copyright 2010 by Pearson Education1
Building Java Programs
Chapter 2
Lecture 3: Variables, For Loops, Nested Loops
reading: 2.2 2.3
(Slides adapted from Stuart Reges, Hlne Martin,and Marty Stepp)
7/27/2019 Pemrograman1 3 Expressions Forloops
2/47
Copyright 2010 by Pearson Education2
7/27/2019 Pemrograman1 3 Expressions Forloops
3/47
Copyright 2010 by Pearson Education3
Variablesreading: 2.2
7/27/2019 Pemrograman1 3 Expressions Forloops
4/47
Copyright 2010 by Pearson Education4
Receipt example
Apakah yg kurang tepat /jelek, pada kode berikut?public class Receipt {
public static void main(String[] args) {// Calculate total owed, assuming 8% tax / 15% tipSystem.out.print("Subtotal: ");System.out.println(38 + 40 + 30);
System.out.print("Tax: ");System.out.println((38 + 40 + 30) * .08);System.out.print("Tip: ");System.out.println((38 + 40 + 30) * .15);System.out.print("Total: ");System.out.println(38 + 40 + 30 +
(38 + 40 + 30) * .08 +(38 + 40 + 30) * .15);}
}
Ekspresi subtotal (38 + 40 + 30) berulang /tdk efisien
Terlalu banyak statement println
7/27/2019 Pemrograman1 3 Expressions Forloops
5/47
Copyright 2010 by Pearson Education5
Variables
variable: satu unit memory komputer yang diberi namadan tipe yang dapat menyimpan satu nilai tertentu.
Seperti pengingat stasion radio pada audio mobil, atau
pengingat nomor phoneBook pada Hp:
Langkah-langkah untuk memakai variabel dlm program:
Mendeklarasikan - memasang /memberi nama and tipe
Menginisialisasi - memberi nilai awal
Menggunakan - cetak / memakainya dalam perhitungan
7/27/2019 Pemrograman1 3 Expressions Forloops
6/47
Copyright 2010 by Pearson Education6
Declaration
variable declaration: Memesan satu lokasi di memory untukmenyimpan satu nilai.
Variabel-variabel harus dideklarasikan dahulu sebelum dapatdigunakan.
Syntax:
typename; Nama adalah sebuahidentifier.
int zipcode;
int kodePos
double myGPA;
double indeksPrestasiKu
zipcode
myGPA
7/27/2019 Pemrograman1 3 Expressions Forloops
7/47Copyright 2010 by Pearson Education
7
Assignment
assignment: Penugasan / adalah menyimpan ataumemberi nilai ke dalam sebuah variabel.
Nilai boleh dalam bentu ekspresi; variabel menyimpan hasilekspresinya.
Syntax:
name = expression;
int zipcode;zipcode = 90210; //literal = ekspresi simple
double myGPA;
myGPA = 1.0 + 2.25; //ekspresi
zipcode 90210
myGPA 3.25
7/27/2019 Pemrograman1 3 Expressions Forloops
8/47Copyright 2010 by Pearson Education8
Menggunakan variabel
Setelah diberi nilai, variabel dpt digunakan dlm ekspresi:int x;
x = 3;
System.out.println("x is " + x); // x is 3
System.out.println(5 * x - 1); // 5 * 3 - 1
Anda dapat memberi nilai ke sebuah
Variabel berkali-kali sesuai kebutuhan:
int x;x = 3;
System.out.println(x + " here"); // 3 here
x = 4 + 7;
System.out.println("now x is " + x); // now x is 11
x 3x 11
7/27/2019 Pemrograman1 3 Expressions Forloops
9/47Copyright 2010 by Pearson Education9
Deklarasi/inisialisasi
Sebuah variabel dapat di deklarasikan /di-inisialisasikandalam sebuah statement tunggal.
Syntax:
typename = value;
double myGPA = 3.95;
int x = (11 % 3) + 12;x 14
myGPA 3.95
7/27/2019 Pemrograman1 3 Expressions Forloops
10/47Copyright 2010 by Pearson Education10
Assignment and algebra
Assignment memakai tanda = , tetapi ini tidak samadengan persamaan pada matematika aljabar.
tanda= berarti, simpan nilai di kanan tanda = ke dalamvariabel di kiri tanda ="
Eksprsi di sebelah kanan di evaluasi terlebih dahulu,
kemudian hasilnya disimpan ke variabel sebelah kiri.
Apakah yang terjadi pada ekspresi di bawah ini?int x = 3;
x = x + 2; // ??? x 3x 5
7/27/2019 Pemrograman1 3 Expressions Forloops
11/47Copyright 2010 by Pearson Education11
Increment dan decrement
shortcuts untuk menambah atau mengurangi sebuah variabledengan nilai 1
ekspresi pendek sama dg ekspresi panjangvariable++; variable = variable + 1;
variable--; variable = variable - 1;
int x = 2;
x++; // x = x + 1;
// x now stores 3double gpa = 2.5;
gpa--; // gpa = gpa - 1;
// gpa now stores 1.5
7/27/2019 Pemrograman1 3 Expressions Forloops
12/47Copyright 2010 by Pearson Education12
Operator Modify-dan-assign
shortcuts untuk memodifikasi nilai variabel
Ekspresi pendek Equivalent ekspresi panjangvariable += value; variable = variable + value;
variable -= value; variable = variable - value;
variable *= value; variable = variable * value;variable /= value; variable = variable / value;
variable %= value; variable = variable % value;
x += 3; // x = x + 3;gpa -= 0.5; // gpa = gpa - 0.5;
number *= 2; // number = number * 2;
7/27/2019 Pemrograman1 3 Expressions Forloops
13/47Copyright 2010 by Pearson Education13
Assignment dan tipe data
Sebuah variabele hanya dapat menyimpan nilai sesuaidenga tipenya.
int x = 2.5; // ERROR: incompatible types
Nilai int dapat disimpan ke dalam variabel double. The value is converted into the equivalent real number.
double myGPA = 4;
double avg = 11 / 2;
Mengapakah avg menyimpan 5.0bukan 5.5 ?
myGPA 4.0
avg 5.0
7/27/2019 Pemrograman1 3 Expressions Forloops
14/47Copyright 2010 by Pearson Education14
Kesalahan kompilasi
Sebuah variabel tidak dapat di pakai sampai kepadanyadiberi satu nilai tertentu.
int x;
System.out.println(x); // ERROR: x has no value
Jangan mendeklarasikan variabel yang sama 2 kali.
int x;int x; // ERROR: x already exists
int x = 3;
int x = 5; // ERROR: x already exists
Bagaimana perbaikan untuk kode di atas?
7/27/2019 Pemrograman1 3 Expressions Forloops
15/47Copyright 2010 by Pearson Education15
Mencetak nilai sebuah variabel
Gunakan tanda + untuk mencetak String dan nilai sebuahvariabel secara langsung dalam satu baris.
double IP = (95.1 + 71.9 + 82.6) / 3.0;
System.out.println(IP anda adalah " + IP);
int mhs = 11 + 17 + 4 + 19 + 14;
System.out.println(Terdapat " + mhs +
" mahasiswa dalam kuliah ini.");
Output:
IP anda adalah 83.2
Terdapat 65 mahasiswa dalam kuliah ini.
7/27/2019 Pemrograman1 3 Expressions Forloops
16/47Copyright 2010 by Pearson Education16
Receipt question
Ubahlah program berikut dg menggunakan variabel.public class Receipt {
public static void main(String[] args) {// Calculate total owed, assuming 8% tax / 15% tipSystem.out.print("Subtotal: ");System.out.println(38 + 40 + 30);
System.out.print("Tax: ");System.out.println((38 + 40 + 30) * .08);
System.out.print("Tip: ");System.out.println((38 + 40 + 30) * .15);
System.out.print("Total: ");System.out.println(38 + 40 + 30 +
(38 + 40 + 30) * .15 +(38 + 40 + 30) * .08);
}
}
7/27/2019 Pemrograman1 3 Expressions Forloops
17/47Copyright 2010 by Pearson Education17
Jawaban program
public class Receipt {public static void main(String[] args) {// Calculate total owed, assuming 8% tax / 15% tipint subtotal = 38 + 40 + 30;double tax = subtotal * .08;double tip = subtotal * .15;double total = subtotal + tax + tip;
System.out.println("Subtotal: " + subtotal);System.out.println("Tax: " + tax);System.out.println("Tip: " + tip);System.out.println("Total: " + total);
}
}
7/27/2019 Pemrograman1 3 Expressions Forloops
18/47Copyright 2010 by Pearson Education18
Building Java Programs
Chapter 2Lecture 2-2: The for Loop
reading: 2.3
7/27/2019 Pemrograman1 3 Expressions Forloops
19/47Copyright 2010 by Pearson Education19
Repetition with for loops
Sejauh ini, aksi berulang menghasilokan kode redudansi:makeBatter();
bakeCookies();
bakeCookies();
bakeCookies();
bakeCookies();
bakeCookies();
frostCookies();
Statement for loop dalam java memfasilitasi perulangantask /tugas.
mixBatter();
for (int i = 1; i
7/27/2019 Pemrograman1 3 Expressions Forloops
20/47Copyright 2010 by Pearson Education
20
for loop syntax
for (initialization; test; update) {statement;
statement;
...
statement;
}
Inisialisasi /initialization hanya dilakukan satu kali saja.
Yang diulangi adalah hal-hal berikut:
Periksa apakah nilai kondisi pengujian/ test bernilai benar. Jika
nilai kondisi pengujian selah, hentikan perulangan.
Eksekusi statement- statement
Lakukan update.
body
header
7/27/2019 Pemrograman1 3 Expressions Forloops
21/47Copyright 2010 by Pearson Education
21
Control structures
Struktur kendali /Control structure: pemrograman adalahsuatu konstruksi yang berdampak pada aliran eksekusiprogram.
Kode-kode yang dikendalikan bisa satu statement ataulebih
Struktur for loop adalah sebuah contoh dari sebuahstruktur pengendalian perulangan /looping.
7/27/2019 Pemrograman1 3 Expressions Forloops
22/47Copyright 2010 by Pearson Education
22
Inisialisai /Initializationfor (
int i = 1; i
7/27/2019 Pemrograman1 3 Expressions Forloops
23/47Copyright 2010 by Pearson Education
23
Testfor (int i = 1;
i = Lebih besar dari atau samadengan /greater than or
equal to
== Sama dengan /exactly equal to
!= Tidak samadengan /not equal to
7/27/2019 Pemrograman1 3 Expressions Forloops
24/47Copyright 2010 by Pearson Education
24
Update
for (int i = 1; i
7/27/2019 Pemrograman1 3 Expressions Forloops
25/47
Copyright 2010 by Pearson Education25
Repetition over a rangeSystem.out.println("1 squared = " + 1 * 1);System.out.println("2 squared = " + 2 * 2);System.out.println("3 squared = " + 3 * 3);System.out.println("4 squared = " + 4 * 4);System.out.println("5 squared = " + 5 * 5);System.out.println("6 squared = " + 6 * 6);
Intuition: "I want to print a line for each number from 1 to 6"
The for loop does exactly that!
for (int i = 1; i
7/27/2019 Pemrograman1 3 Expressions Forloops
26/47
Copyright 2010 by Pearson Education26
Loop walkthrough
for (int i = 1; i
7/27/2019 Pemrograman1 3 Expressions Forloops
27/47
Copyright 2010 by Pearson Education27
Multi-line loop bodySystem.out.println("+----+");
for (int i = 1; i
7/27/2019 Pemrograman1 3 Expressions Forloops
28/47
Copyright 2010 by Pearson Education28
Expressions for counter
int highTemp = 5;for (int i = -3; i
7/27/2019 Pemrograman1 3 Expressions Forloops
29/47
Copyright 2010 by Pearson Education29
System.out.print
Prints without moving to a new line allows you to print partial messages on the same line
int highestTemp = 5;
for (int i = -3; i
7/27/2019 Pemrograman1 3 Expressions Forloops
30/47
Copyright 2010 by Pearson Education30
Counting down
The update can use -- to make the loop count down. The test must say > instead of= 1; i--) {
System.out.print(i + ", ");}
System.out.println("blastoff!");
System.out.println("The end.");
Output:T-minus 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, blastoff!
The end.
7/27/2019 Pemrograman1 3 Expressions Forloops
31/47
Copyright 2010 by Pearson Education31
Nested loopsreading: 2.3
7/27/2019 Pemrograman1 3 Expressions Forloops
32/47
Copyright 2010 by Pearson Education32
Nested loops
nested loop: perulangan yang terletak pada perulanganlainnya.
for (int i = 1; i
7/27/2019 Pemrograman1 3 Expressions Forloops
33/47
Copyright 2010 by Pearson Education33
Nested for loop exercise
Apakah hasil dari perulangan for dibawah ini?for (int i = 1; i
7/27/2019 Pemrograman1 3 Expressions Forloops
34/47
Copyright 2010 by Pearson Education34
Nested for loop exercise
Apakah hasil dari perulangan for dibawah ini?for (int i = 1; i
7/27/2019 Pemrograman1 3 Expressions Forloops
35/47
Copyright 2010 by Pearson Education35
Common errors
Both of the following sets of code produce infinite loops:for (int i = 1; i
7/27/2019 Pemrograman1 3 Expressions Forloops
36/47
Copyright 2010 by Pearson Education36
Complex lines
What nested for loops produce the following output?
....1
...2
..3
.4
5
We must build multiple complex lines of output using: an outer "vertical" loop for each of the lines
inner "horizontal" loop(s) for the patterns within each line
outer loop (loops 5 times because there are 5 lines)
inner loop (repeated characters on each line)
7/27/2019 Pemrograman1 3 Expressions Forloops
37/47
Copyright 2010 by Pearson Education37
Outer and inner loop
First write the outer loop, from 1 to the number of lines.for (int line = 1; line
7/27/2019 Pemrograman1 3 Expressions Forloops
38/47
Copyright 2010 by Pearson Education38
Mapping loops to numbersfor (int count = 1; count
7/27/2019 Pemrograman1 3 Expressions Forloops
39/47
Copyright 2010 by Pearson Education39
Loop tables
What statement in the body would cause the loop to print:2 7 12 17 22
To see patterns, make a table ofcount and the numbers.
Each time count goes up by 1, the number should go up by 5.
But count * 5 is too great by 3, so we subtract 3.
count number to print 5 * count
1 2 5
2 7 103 12 15
4 17 20
5 22 25
5 * count - 3
2
712
17
22
7/27/2019 Pemrograman1 3 Expressions Forloops
40/47
Copyright 2010 by Pearson Education40
Loop tables question
What statement in the body would cause the loop to print:17 13 9 5 1
Let's create the loop table together. Each time count goes up 1, the number printed should ...
But this multiple is off by a margin of ...
count number to print
1 17
2 133 9
4 5
5 1
-4 * count -4 * count + 21
-4 17
-8 13-12 9
-16 5
-20 1
-4 * count
-4
-8-12
-16
-20
7/27/2019 Pemrograman1 3 Expressions Forloops
41/47
Copyright 2010 by Pearson Education41
Another view: Slope-intercept
The next three slides present the mathematical basis forthe loop tables. Feel free to skip it.
-10
-5
0
5
10
15
20
25
-2 0 2 4 6
count (x) number to print (y)
1 2
2 7
3 12
4 17
5 22
7/27/2019 Pemrograman1 3 Expressions Forloops
42/47
Copyright 2010 by Pearson Education42
Another view: Slope-intercept Caution: This is algebra, not assignment!
Recall: slope-intercept form (y = mx + b)
Slope is defined as rise over run (i.e. rise / run). Since the run isalways 1 (we increment along x by 1), we just need to look at therise. The rise is the difference between the y values. Thus, the
slope (m) is the difference between y values; in this case, it is +5.
To compute the y-intercept (b), plug in the value ofy at x = 1 andsolve for b. In this case, y = 2.
y = m * x + b
2 = 5 * 1 + b
Then b = -3
So the equation isy = m * x + b
y = 5 * x 3
y = 5 * count - 3
count (x) number to print (y)
1 2
2 7
3 12
4 17
5 22
7/27/2019 Pemrograman1 3 Expressions Forloops
43/47
Copyright 2010 by Pearson Education43
Another view: Slope-intercept
Algebraically, if we always take the value ofy atx = 1, then we can solve for b as follows:y = m * x + b
y1 = m * 1 + b
y1 = m + b
b = y1m
In other words, to get the y-intercept, just subtractthe slope from the first y value (b = 2 5 = -3) This gets us the equation
y = m * x + by = 5 * x 3
y = 5 * count 3
(which is exactly the equation from the previous slides)
7/27/2019 Pemrograman1 3 Expressions Forloops
44/47
Copyright 2010 by Pearson Education44
Nested for loop exercise
Make a table to represent any patterns on each line.....1
...2
..3
.4
5
To print a character multiple times, use a for loop.
for (int j = 1; j
7/27/2019 Pemrograman1 3 Expressions Forloops
45/47
Copyright 2010 by Pearson Education45
Nested for loop solution
Answer:for (int line = 1; line
7/27/2019 Pemrograman1 3 Expressions Forloops
46/47
Copyright 2010 by Pearson Education46
Nested for loop exercise
What is the output of the following nested for loops?for (int line = 1; line
7/27/2019 Pemrograman1 3 Expressions Forloops
47/47
Nested for loop exercise
Modify the previous code to produce this output:....1...2.
..3..
.4...
5....
Answer:for (int line = 1; line