1 / 35

Pertemuan 3

Pertemuan 3. Array dkk. ARRAY. Tipe 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.

bette
Download Presentation

Pertemuan 3

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Pertemuan 3 Array dkk

  2. ARRAY • Tipe 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

  3. Contoh program • Program 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.

  4. STRUCT • Tipe data turunan. • Contoh deklarasi : struct { int jari_jari; float luas; float keliling; } lingkaran;

  5. STRUCT Contd. • SATU variabelbisamenyimpan BANYAK data yang BERBEDA TIPE datanya. Mempunyai ELEMEN. • Struktur data : • Konsep: struct of struct (nested struct). 10 314.0 62.8

  6. Contoh program • Program tentang lingkaran. • Algoritma : • Inventarisasi atribut-atribut yang dimiliki oleh sebuah objek lingkaran. • Akses masing-masing elemen dengan memakai operator tanda titik (.).

  7. ARRAY OF STRUCT • Struktur data berupa array yang setiap elemennya bertipe struct. • Contoh deklarasi : struct { int NPM; char nama[30]; float IPK; } mhs[100];

  8. 100 101 102 103 Abdullah Budi Candra Daud 3.80 3.45 3.22 3.17 Array of Struct Contd. • Struktur data : • Untukakseselemendimulaidariindeks array kemudiandiikutinamaelemennya mhs[3].NPM = 1234;

  9. Contoh Program • Program data mahasiswa. • Program tabel fungsi kuadrat.

  10. Tugas Kelompok - RESUME ARRAY • Array as function parameter • String • Two dimensional array STRUCT • Array of structure • Unions • Struct as function parameter

  11. Review BP Dari slide pakcahyopertemuan 7 danpertemuan 2 dengansedikitmodifikasi

  12. Array Review BP

  13. Arrays • An 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 values • An array of int values

  14. The Need for Arrays • Write 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?

  15. The Problem: import java.util.; publicclassExamScoresForLoop { publicstaticvoid main(String[] args) { Scanner keyboard = new Scanner (System.in); double score; double total = 0.0; for(inti = 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??? } } • We need to keep track of each score that is entered by the user in an efficient manner.

  16. score 0x0010 score 98.9 0x0h40 0x0010 50.5 0x0h41 75.0 0x0h42 in this case, score is considered to be a reference to the array at the memory address stored. 59.5 0x0h43 65.4 0x0h44 Using Arrays • Instead of only storing one score: 98.9 • We need to store a collection of scores, or what is called an array. 0x0h40

  17. Index representing position of the data 0 98.9 1 score[0] 2 50.5 75.0 3 score[3] 59.5 4 65.4 Accessing Array Elements • Once 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

  18. Declaring Arrays • An array is declared by: • specifying the type of data it will hold • specifying the name of the array with an identifier • including square brackets [ ] • Syntax: <data type>[] <identifier>; • Examples int[] num; // an array of ints double[] score; // an array of doubles Student[] st; // an array of Student objects

  19. Creating Arrays • In 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 = newint[10]; //creates an array to store 10 integers • It may also be instantiated in two steps: int[] num; num = newint[10];

  20. Initializer Lists • An 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'}

  21. Bounds Checking • An 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.

  22. Traversing Arrays • We 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.

  23. Searching an Array • We 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 name • Start from i = 0 • assume that it is notfound • While 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)

  24. Calculations • We often need to perform calculations using some or all of the elements of the array: • total of all elements • the average • the element with the largest or smallest value • Assume that an array of double values has been declared and filled: double[] score = new double[10];

  25. Finding the Total and Average • In 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 (inti = 0; i < score.length; i++) { total = total + score[i]; } System.out.println("The total is " + total); doubleavg = total / score.length; System.out.println("The average is " + avg);

  26. Arrays and Methods • Arrays 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 employees • the second parameter is a String representing the name of the employee required • The method should return the position of the employee whose name is found based on the second parameter.

  27. Arrays as Parameters • The method can be defined as follows: publicstaticintfindEmp(String[] name, String wanted) { for(inti = 0; i < name.length; i++) if (wanted.equalsIgnoreCase(name[i])) returni; // found at pos i return -1; // not found }

  28. Arrays as Returned Objects • Arrays 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. publicstaticint[] findLengths(String[] strArray) {int[] strLength = newint[strArray.length]; for (inti = 0; i < strArray.length; i++) strLength[i] = strArray[i].length(); returnstrLength; }

  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.

  30. CLASS Review BP

  31. Class adalah template untukpembuatanobyek • Class memilikianggota : • Atribut • Method

  32. multi-line comments name of the class in-linecomments statementsto be executed Anatomy of a Java Class • A 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 5 System.out.print("num1 has value "); System.out.println(num1); } }

  33. class header mainmethod Anatomy of a Java Class • A 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 5 System.out.print("num1 has value "); System.out.println(num1); } }

  34. Contoh class tabungan class 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

  35. Contohpenggunaan class tabungan class BankApp { public static void main(String[] args) { // create acct BankAccount ba1 = new BankAccount(100.00); System.out.print("Before transactions, "); // output : Before transactions, balance=100 ba1.display(); // display balance ba1.deposit(74.35); // make deposit ba1.withdraw(20.00); // make withdrawal System.out.print("After transactions, "); // output : After transactions, balance=154.35 ba1.display(); // display balance } // end main() } // end class BankApp

More Related