Array dkk. Tipe data turunan. Contoh deklarasi : int x[20]; SATU variabel untuk menyimpan BANYAK...

35
Array dkk Pertemuan 3

Transcript of Array dkk. Tipe data turunan. Contoh deklarasi : int x[20]; SATU variabel untuk menyimpan BANYAK...

Page 1: Array dkk. Tipe data turunan. Contoh deklarasi : int x[20]; SATU variabel untuk menyimpan BANYAK data dengan TIPE data yang SAMA. Mempunyai INDEKS. Struktur.

Array dkk

Pertemuan 3

Page 2: Array dkk. Tipe data turunan. Contoh deklarasi : int x[20]; SATU variabel untuk menyimpan BANYAK data dengan TIPE data yang SAMA. Mempunyai INDEKS. Struktur.

ARRAYTipe data turunan.Contoh deklarasi : int x[20];SATU variabel untuk menyimpan BANYAK

data dengan TIPE data yang SAMA. Mempunyai INDEKS.

Struktur data : Alokasi memori bersifat statis/ tetap.Konsep : string, array multidimensi

4 3 2 1 7

Page 3: Array dkk. Tipe data turunan. Contoh deklarasi : int x[20]; SATU variabel untuk menyimpan BANYAK data dengan TIPE data yang SAMA. Mempunyai INDEKS. Struktur.

Contoh programProgram menghitung rata-rata nilai.Algoritma :

Deklarasikan variabel array untuk menyimpan data-data nilai.

Input data nilai dengan perintah looping. Akses elemen dengan operator kurung siku ([]).

Hitung penjumlahan data-data nilai.Hitung rata-rata = jumlah total/ jumlah data.

Page 4: Array dkk. Tipe data turunan. Contoh deklarasi : int x[20]; SATU variabel untuk menyimpan BANYAK data dengan TIPE data yang SAMA. Mempunyai INDEKS. Struktur.

STRUCTTipe data turunan.Contoh deklarasi :

struct {int jari_jari;float luas;float keliling;

} lingkaran;

Page 5: Array dkk. Tipe data turunan. Contoh deklarasi : int x[20]; SATU variabel untuk menyimpan BANYAK data dengan TIPE data yang SAMA. Mempunyai INDEKS. Struktur.

STRUCT Contd.SATU variabel bisa menyimpan BANYAK data

yang BERBEDA TIPE datanya. Mempunyai ELEMEN.

Struktur data :

Konsep : struct of struct (nested struct).

10

314.0

62.8

Page 6: Array dkk. Tipe data turunan. Contoh deklarasi : int x[20]; SATU variabel untuk menyimpan BANYAK data dengan TIPE data yang SAMA. Mempunyai INDEKS. Struktur.

Contoh programProgram tentang lingkaran.Algoritma :

Inventarisasi atribut-atribut yang dimiliki oleh sebuah objek lingkaran.

Akses masing-masing elemen dengan memakai operator tanda titik (.).

Page 7: Array dkk. Tipe data turunan. Contoh deklarasi : int x[20]; SATU variabel untuk menyimpan BANYAK data dengan TIPE data yang SAMA. Mempunyai INDEKS. Struktur.

ARRAY OF STRUCTStruktur data berupa array yang setiap

elemennya bertipe struct.Contoh deklarasi :

struct {int NPM;char nama[30];float IPK;

} mhs[100];

Page 8: Array dkk. Tipe data turunan. Contoh deklarasi : int x[20]; SATU variabel untuk menyimpan BANYAK data dengan TIPE data yang SAMA. Mempunyai INDEKS. Struktur.

Array of Struct Contd.Struktur data :

Untuk akses elemen dimulai dari indeks array kemudian diikuti nama elemennya mhs[3].NPM = 1234;

100

Abdullah

3.80

101

Budi

3.45

102

Candra

3.22

103

Daud

3.17

Page 9: Array dkk. Tipe data turunan. Contoh deklarasi : int x[20]; SATU variabel untuk menyimpan BANYAK data dengan TIPE data yang SAMA. Mempunyai INDEKS. Struktur.

Contoh ProgramProgram data mahasiswa.Program tabel fungsi kuadrat.

Page 10: Array dkk. Tipe data turunan. Contoh deklarasi : int x[20]; SATU variabel untuk menyimpan BANYAK data dengan TIPE data yang SAMA. Mempunyai INDEKS. Struktur.

Tugas Kelompok - RESUMEARRAY Array as function parameter String Two dimensional arraySTRUCT Array of structure Unions Struct as function parameter

Page 11: Array dkk. Tipe data turunan. Contoh deklarasi : int x[20]; SATU variabel untuk menyimpan BANYAK data dengan TIPE data yang SAMA. Mempunyai INDEKS. Struktur.

Review BPDari slide pak cahyo pertemuan 7 dan pertemuan 2

dengan sedikit modifikasi

Page 12: Array dkk. Tipe data turunan. Contoh deklarasi : int x[20]; SATU variabel untuk menyimpan BANYAK data dengan TIPE data yang SAMA. Mempunyai INDEKS. Struktur.

ArrayReview BP

Page 13: Array dkk. Tipe data turunan. Contoh deklarasi : int x[20]; SATU variabel untuk menyimpan BANYAK data dengan TIPE data yang SAMA. Mempunyai INDEKS. Struktur.

13

ArraysAn array is a special kind of object that is

used to store a collection of data.The data stored in an array must all be of

the same type, whether primitive or reference data types.

For example, we may want to store:An array of double valuesAn array of int values

Page 14: Array dkk. Tipe data turunan. Contoh deklarasi : int x[20]; SATU variabel untuk menyimpan BANYAK data dengan TIPE data yang SAMA. Mempunyai INDEKS. Struktur.

14

The Need for ArraysWrite a Java program that asks the user for

10 exam scores and displays the average.What if you are also required to display all

the scores which are higher than the average?

What if you are to record 100 scores?

Page 15: Array dkk. Tipe data turunan. Contoh deklarasi : int x[20]; SATU variabel untuk menyimpan BANYAK data dengan TIPE data yang SAMA. Mempunyai INDEKS. Struktur.

15

The Problem:

We need to keep track of each score that is entered by the user in an efficient manner.

import java.util.;public class ExamScoresForLoop{

public static void main(String[] args){Scanner keyboard = new Scanner (System.in);double score;double total = 0.0;for(int i = 1; i <= 10; i++)

{System.out.println("Enter score " + i +":");score = keyboard.nextDouble();total = total + score;}System.out.println("The average score is " + total/10);

// how to display scores which are greater than average???}

}

Page 16: Array dkk. Tipe data turunan. Contoh deklarasi : int x[20]; SATU variabel untuk menyimpan BANYAK data dengan TIPE data yang SAMA. Mempunyai INDEKS. Struktur.

16

Using Arrays

Instead of only storing one score:score

0x0010

We need to store a collection of scores, or what is called an array.

score0x0010

0x0h40

0x0h41

0x0h42

0x0h43

0x0h44

98.9

98.9

50.5

75.0

59.5

65.4

0x0h40

in this case, score is considered to be a reference to the array at the memory address stored.

Page 17: Array dkk. Tipe data turunan. Contoh deklarasi : int x[20]; SATU variabel untuk menyimpan BANYAK data dengan TIPE data yang SAMA. Mempunyai INDEKS. Struktur.

17

Accessing Array ElementsOnce an array has been declared, we can

store and access data in it.We must specify the index representing the

position of the data.The index always begins from 0.

score 98.9

50.5

75.0

59.5

65.4

0

1

2

3

4

Index representing position of the data

score[0]

score[3]

Page 18: Array dkk. Tipe data turunan. Contoh deklarasi : int x[20]; SATU variabel untuk menyimpan BANYAK data dengan TIPE data yang SAMA. Mempunyai INDEKS. Struktur.

18

Declaring ArraysAn array is declared by:

specifying the type of data it will holdspecifying the name of the array with an

identifierincluding square brackets [ ]

Syntax:<data type>[] <identifier>;

Examplesint[] num; // an array of intsdouble[] score; // an array of doubles Student[] st; // an array of Student objects

Page 19: Array dkk. Tipe data turunan. Contoh deklarasi : int x[20]; SATU variabel untuk menyimpan BANYAK data dengan TIPE data yang SAMA. Mempunyai INDEKS. Struktur.

19

Creating ArraysIn Java, the array is an object and must be

instantiated with its size.Syntax:

<identifier> = new <data type>[<size>];Therefore, an array may be declared and

instantiated in one statement:int[] num = new int[10]; //creates an array to store 10 integers

It may also be instantiated in two steps:int[] num;num = new int[10];

Page 20: Array dkk. Tipe data turunan. Contoh deklarasi : int x[20]; SATU variabel untuk menyimpan BANYAK data dengan TIPE data yang SAMA. Mempunyai INDEKS. Struktur.

20

Initializer ListsAn array can also be created by using an

initializer list that fills in the values of the elements in the array in one line.

When an initializer list is used, the new operator and size of the array are not specified.

Examples:int[] num = {3, 6, 5, 7, 2, 8, 10, 20}char[] letterGrades = {'A', 'B', 'C', 'D', 'F'}

Page 21: Array dkk. Tipe data turunan. Contoh deklarasi : int x[20]; SATU variabel untuk menyimpan BANYAK data dengan TIPE data yang SAMA. Mempunyai INDEKS. Struktur.

21

Bounds CheckingAn array that has been instantiated has a

fixed size.int[] num = new int[10] has array elements

from num[0] to num[9] only.The Java interpreter will indicate an out-

of-bounds error at run-time if the array index is not valid.

Each array object has an attribute length that stores the size of the array, or the number of elements.

Therefore an array will have valid indices from 0 to (length-1) only.

Page 22: Array dkk. Tipe data turunan. Contoh deklarasi : int x[20]; SATU variabel untuk menyimpan BANYAK data dengan TIPE data yang SAMA. Mempunyai INDEKS. Struktur.

22

Traversing ArraysWe can use a for loop to traverse the array For example, we may display each

element of the array:for (int i = 0; i < maks; i++){System.out.println(data[i]);

}We may even use a for loop to allow the

user to enter the elements of the array via interactive input.

Page 23: Array dkk. Tipe data turunan. Contoh deklarasi : int x[20]; SATU variabel untuk menyimpan BANYAK data dengan TIPE data yang SAMA. Mempunyai INDEKS. Struktur.

23

Searching an ArrayWe may need to check if an element is in the

array:We can use the following logic to check whether a

name that the user enters is in the array of names declared and filled earlier:ask user for the required nameStart from i = 0assume that it is not foundWhile the required name is not found and i <

length of array if the value at position i corresponds to the required

name then the name is found

otherwise,check the next element (i = i + 1)

Page 24: Array dkk. Tipe data turunan. Contoh deklarasi : int x[20]; SATU variabel untuk menyimpan BANYAK data dengan TIPE data yang SAMA. Mempunyai INDEKS. Struktur.

24

CalculationsWe often need to perform calculations

using some or all of the elements of the array:total of all elementsthe averagethe element with the largest or smallest value

Assume that an array of double values has been declared and filled:double[] score = new double[10];

Page 25: Array dkk. Tipe data turunan. Contoh deklarasi : int x[20]; SATU variabel untuk menyimpan BANYAK data dengan TIPE data yang SAMA. Mempunyai INDEKS. Struktur.

25

Finding the Total and AverageIn order to find the total, we must initialize and

keep track of the running total.The total is then used to calculate the average.

double total = 0.0;for (int i = 0; i < score.length; i++){

total = total + score[i];}System.out.println("The total is " + total);double avg = total / score.length;System.out.println("The average is " + avg);

Page 26: Array dkk. Tipe data turunan. Contoh deklarasi : int x[20]; SATU variabel untuk menyimpan BANYAK data dengan TIPE data yang SAMA. Mempunyai INDEKS. Struktur.

26

Arrays and MethodsArrays can be used as parameters in

methods: the entire array is passed to the method.

For example, write a method findEmp that receives two parameters:the first parameter is an array of Strings

representing names of employeesthe second parameter is a String representing

the name of the employee requiredThe method should return the position of

the employee whose name is found based on the second parameter.

Page 27: Array dkk. Tipe data turunan. Contoh deklarasi : int x[20]; SATU variabel untuk menyimpan BANYAK data dengan TIPE data yang SAMA. Mempunyai INDEKS. Struktur.

27

Arrays as Parameters

The method can be defined as follows:

public static int findEmp(String[] name, String wanted){

for(int i = 0; i < name.length; i++)if (wanted.equalsIgnoreCase(name[i]))

return i; // found at pos i

return -1; // not found}

Page 28: Array dkk. Tipe data turunan. Contoh deklarasi : int x[20]; SATU variabel untuk menyimpan BANYAK data dengan TIPE data yang SAMA. Mempunyai INDEKS. Struktur.

28

Arrays as Returned ObjectsArrays can also be returned by methods,

as long as the array type is specified as the return type.

The following method takes as input an array of Strings and returns another array with the lengths of each of the Strings in the array.

public static int[] findLengths(String[] strArray){

int[] strLength = new int[strArray.length];for (int i = 0; i < strArray.length; i++)

strLength[i] = strArray[i].length();return strLength;

}

Page 29: Array dkk. Tipe data turunan. Contoh deklarasi : int x[20]; SATU variabel untuk menyimpan BANYAK data dengan TIPE data yang SAMA. Mempunyai INDEKS. Struktur.

29

Initial Values of Array Elements

All elements in an array are automatically initialised with default values.

An array of numeric data has default elements with value 0 double[] score = new double[10];all elements in score will have value 0.0

Arrays of boolean will be initialized to false.

Arrays of reference data types will be initialized to null.

Page 30: Array dkk. Tipe data turunan. Contoh deklarasi : int x[20]; SATU variabel untuk menyimpan BANYAK data dengan TIPE data yang SAMA. Mempunyai INDEKS. Struktur.

CLASSReview BP

Page 31: Array dkk. Tipe data turunan. Contoh deklarasi : int x[20]; SATU variabel untuk menyimpan BANYAK data dengan TIPE data yang SAMA. Mempunyai INDEKS. Struktur.

Class adalah template untuk pembuatan obyek

Class memiliki anggota :AtributMethod

Page 32: Array dkk. Tipe data turunan. Contoh deklarasi : int x[20]; SATU variabel untuk menyimpan BANYAK data dengan TIPE data yang SAMA. Mempunyai INDEKS. Struktur.

Anatomy of a Java ClassA Java console application must consist of

one class that has the following structure: /* This is a sample program only. Written by: Date: */public class SampleProgram{

public static void main(String [] args){

int num1 = 5; // num stores 5System.out.print("num1 has value ");

System.out.println(num1);}

}

multi-line comments

in-linecomments

name of the class

statementsto be executed

Page 33: Array dkk. Tipe data turunan. Contoh deklarasi : int x[20]; SATU variabel untuk menyimpan BANYAK data dengan TIPE data yang SAMA. Mempunyai INDEKS. Struktur.

Anatomy of a Java ClassA Java console application must consist of

one class that has the following structure: /* This is a sample program only. Written by: Date: */public class SampleProgram{

public static void main(String [] args){

int num1 = 5; // num stores 5System.out.print("num1 has value ");

System.out.println(num1);}

}

class header

mainmethod

Page 34: Array dkk. Tipe data turunan. Contoh deklarasi : int x[20]; SATU variabel untuk menyimpan BANYAK data dengan TIPE data yang SAMA. Mempunyai INDEKS. Struktur.

Contoh class tabunganclass BankAccount{ private double balance; // account balance public BankAccount(double openingBalance) { // constructor balance = openingBalance; } public void deposit(double amount) { // makes deposit balance = balance + amount; } public void withdraw(double amount) { // makes withdrawal

balance = balance – amount; } public void display(){ // displays balance System.out.println("balance=" + balance); }} // end class BankAccount

Page 35: Array dkk. Tipe data turunan. Contoh deklarasi : int x[20]; SATU variabel untuk menyimpan BANYAK data dengan TIPE data yang SAMA. Mempunyai INDEKS. Struktur.

Contoh penggunaan class tabungan

class BankApp{ public static void main(String[] args) {

// create acctBankAccount ba1 = new BankAccount(100.00); System.out.print("Before transactions, ");// output : Before transactions, balance=100ba1.display(); // display balanceba1.deposit(74.35); // make depositba1.withdraw(20.00); // make withdrawalSystem.out.print("After transactions, ");// output : After transactions, balance=154.35ba1.display(); // display balance

} // end main()} // end class BankApp