1 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.

Slides:



Advertisements
Similar presentations
IS Programming Fundamentals 1 (Lec) Date: September 14, Array.
Advertisements

UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1.
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Basic Java Constructs and Data Types – Nuts and Bolts
Classes and Objects in Java
11 Copyright © 2005, Oracle. All rights reserved. Using Arrays and Collections.
Introduction to arrays Array One dimenstional array.
Introduction to Programming
Introduction to Programming
Introduction to Programming Java Lab 5: Boolean Operations 8 February JavaLab5 lecture slides.ppt Ping Brennan
Introduction to Programming
Data Structures ADT List
John Hurley Cal State LA
The ArrayList Class and the enum Keyword
Two Dimensional Arrays and ArrayList
1 Lecture 16/3/11: Contents Example of an array of user-defined objects: Car and Carr Constructor Providing functionalities for a user- defined object.
Programming Methodology (1). public class Hello { public static void main(String[] args) { System.out.println("Hello world"); } } Hello world.
1 public class Newton { public static double sqrt(double c) { double epsilon = 1E-15; if (c < 0) return Double.NaN; double t = c; while (Math.abs(t - c/t)
Chapter 8: Arrays.
EXAMPLES (Arrays). Example Many engineering and scientific applications represent data as a 2-dimensional grid of values; say brightness of pixels in.
1.A computer game is an example of A.system software; B.a compiler; C.application software; D.hardware; E.none of the above. 2.JVM stands for: A.Java Virtual.
Firefly Synchronisation Java Demo in 1D Array. 1 Dimension Firefly in Java two neighbors 1. Initialization: 2.
1 Review Quisioner Kendala: Kurang paham materi. Praktikum Pengaruh teman.
Arrays.
Purpose : To convert this string to a new character array. Return Type : char[ ] Parameters : none Declaration : public char[ ] toCharArray() Returns.
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Review BP Dari slide pak cahyo pertemuan 7 dan pertemuan 2 dengan sedikit modifikasi.
Loops –Do while Do While Reading for this Lecture, L&L, 5.7.
Computer Programming Lab(7).
1 Arrays and Strings Chapter 9 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores :
Chapter 3 Flow of Control Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Objects contains data and methods Class – type of object Create class first Then object or instance String – defined class String s; // creates instance.
CS110 Programming Language I
Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-2: Arrays as Parameters reading: , 3.3 self-checks: Ch. 7 #5, 8,
Lecture 9: More on objects, classes, strings discuss hw3 assign hw4 default values for variables scope of variables and shadowing null reference and NullPointerException.
Chapter 7 Strings F To process strings using the String class, the StringBuffer class, and the StringTokenizer class. F To use the String class to process.
1 Various Methods of Populating Arrays Randomly generated integers.
Pertemuan 3 Array dkk jual [Valdo] Lunatik Chubby Stylus.
CS102--Object Oriented Programming Discussion 2: (programming strategy in java) – Two types of tasks – The use of arrays Copyright © 2008 Xiaoyan Li.
Lecture 15 Arrays: Part 1 COMP1681 / SE15 Introduction to Programming.
© The McGraw-Hill Companies, 2006 Chapter 5 Arrays.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 1 CMT1000: Introduction to Programming Ed Currie Lecture 5a: Input and.
Java Unit 9: Arrays Declaring and Processing Arrays.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Lecture # 8 Constructors Overloading. Topics We will discuss the following main topics: – Static Class Members – Overloaded Methods – Overloaded Constructors.
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
Chapter 8: Collections: Arrays. 2 Objectives One-Dimensional Arrays Array Initialization The Arrays Class: Searching and Sorting Arrays as Arguments The.
1 BUILDING JAVA PROGRAMS CHAPTER 7.1 ARRAY BASICS.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
Lecture 18/19 Arrays COMP1681 / SE15 Introduction to Programming.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Methods (a.k.a. Functions)
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
1 CSC 201: Computer Programming I Lecture 2 B. S. Afolabi.
CMSC 202 Arrays 2 nd Lecture. Aug 6, Array Parameters Both array indexed variables and entire arrays can be used as arguments to methods –An indexed.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
Arrays Chapter 6. Objectives learn about arrays and how to use them in Java programs learn how to use array parameters and how to define methods that.
Two Dimensional Arrays Found in chapter 8, Section 8.9.
int [] scores = new int [10];
For Friday Read No quiz Program 6 due. Program 6 Any questions?
Chapter 9 Introduction to Arrays Fundamentals of Java.
Arrays Chap. 9 Storing Collections of Values 1. Introductory Example Problem: Teachers need to be able to compute a variety of grading statistics for.
For Friday Finish reading chapter 9 WebCT quiz 17.
Chapter VII: Arrays.
Object Oriented Programming in java
Arrays in Java.
Unit-1 Introduction to Java
Presentation transcript:

1 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

2 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?

3 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??? }

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

5 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 Index representing position of the data score[0] score[3]

6 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: [] ; Examples int[] num;// an array of ints double[] score;// an array of doubles Student[] st;// an array of Student objects

7 Creating Arrays In Java, the array is an object and must be instantiated with its size. Syntax: = new [ ]; 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];

8 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'}

9 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.

10 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.

11 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 not found –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)

12 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];

13 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 (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);

14 Finding Maximum Values In order to find the maximum value in an array, we must remember that: –we usually consider an array one element at a time, in order. Assume that a double array score has been declared and filled: double maxScore = score[0] // assume max at pos 0 for (int i = 1; i < score.length; i++) { if (score[i] > maxScore) maxScore = score[i]; // new max found } System.out.println("The maximum value is " + maxScore);

15 Example We can solve the earlier problem now using arrays: Write a Java program that: –asks the user how many scores there, then allows the user to enter the scores. –After the scores have been entered, calculate the average. –Also display all the scores which are higher than the average and display the highest score.

16 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.

17 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 }

18 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. 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; }

19 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.