Arrays and Lists CSC 121 Fall 2014 Howard Rosenthal

Size: px
Start display at page:

Download "Arrays and Lists CSC 121 Fall 2014 Howard Rosenthal"

Transcription

1 Arrays and Lists CSC 121 Fall 2014 Howard Rosenthal

2 Lesson Goals Understand what an array is Understand how to declare arrays Understand what reference variables are Understand how to pass arrays to methods Understand basic sorting Understand linear and binary searching Understand multi-dimensional arrays 2

3 Fundamentals (1) An array is an object that is used to store a list of values. It is made out of a contiguous block of memory that is divided into a number of cells. Each cell holds a value, and all the values are of the same type. Sometimes the cells of an array are called slots. In the example array pictured at right, each cell holds an int. The name of this array is data. The cells are indexed 0 through 9. Each cell can be accessed by using its index. For example, data[0] is the cell which is indexed by zero (which contains the value 23). data[5] is the cell which is indexed by 5 (which contains the value 14). 3

4 Fundamentals (2) The cells are in an array are numbered sequentially starting at zero. If there are N cells in an array, the indexes will be 0 through N-1 Sometimes the index is called a subscript. The expression data[5] is usually pronounced "data-sub-five The value stored in a cell of an array is sometimes called an element of the array. An array has a fixed number of cells, but the values placed in those cells (the elements) may change over time. Every cell of an array holds a value of the same type. So, for example, you can have an array of int, an array of double, and so on. 4

5 Declaring Arrays In order to use arrays, you must learn the basic syntax An array is a named sequence of contiguous memory locations capable of holding a collection of data of the same type You can declare an array in two ways: type[] name or type name[] The first format is more typically used Examples: int[] myarray double[] numbers Declaring the variable creates a reference address in memory 5

6 Reference Variables There are two types of variables in Java primitive and reference Primitive variables are byte, short, int, long, double, float, boolean and char Reference variables hold memory addresses Declaring an array in Java creates a reference variable that holds a memory address i.e. boolean[] truthful truthful is a reference variable that holds an address, not a boolean value truthful[0] would hold a boolean value at the first address in the array 6

7 Array Instantiation There are several ways to instantiate an array. Both require using the new operator Declare and instantiate in two statements type[] name; double[] earnings; name = new type[size] ; earnings = new double[6]; Declare and instantiate in one statement type[] name = new type[size]; double[] earnings = new double[6]; Declare, instantiate and initialize in one statement type[] name = v 0, v 1, v 2 v n-1 ; double[] earnings = 25.2, 35.9, 72.6, 12.8, 176.4, 99.0; 7

8 Array Instantiation Basic Rules The values in an array must all be of the same data type The first index in the array is 0 An array is referenced from name[0] name[size-1] The elements of an array are always initialized to 0 by type boolean arrays are initialized to false char initializes to the null character Any reference type initializes to null 8

9 Instant Check Write the statement(s) necessary to instantiate: - a boolean type honesty with size 7 - a short type days with size 365 9

10 Bound Checking in Arrays The length of an array is how many cells it has. An array of length N has cells indexed 0..(N-1) Indexes must be an integer type greater than or equal to 0. If an expression is always illegal it will be caught at compile time However, if an index is found to be illegal during execution an exception message will appear and the program is terminated 10

11 Bound Checking in Arrays - Examples Given: int[] data = new int[10]; Example Outcome data[ -1 ] always illegal index must be >= 0 data[ 10 ] data[ 1.5 ] data[ 0 ] data[ 9 ] data[ j ] illegal out of range (given the above declaration) always illegal must be an integer always OK OK (given the above declaration) can't tell (depends on the value of j) 11

12 Using an Expression as an Index class ArrayExample public static void main ( String[] args ) double[] val = new double[4]; val[0] = 0.12; val[1] = 1.43; val[2] = 2.98; int j = 3; System.out.println( "cell 4: " + val[ j ] ); System.out.println( "cell 3: " + val[ j-1 ] ); j = j-2; System.out.println( "cell 2: " + val[ j ] ); 12

13 Copying Values from Cell to Cell public class ArrayExample public static void main ( String[] args ) int[] vala = 12, 23, 45, 56 ; int[] valb = new int[4]; valb[ 0 ] = vala[ 0 ] ; valb[ 1 ] = vala[ 1 ] ; valb[ 2 ] = vala[ 2 ] ; valb[ 3 ] = vala[ 3 ] ; 13

14 Arrays and Methods(1) Passing an Array to a Method An array reference can be passed as a parameter to a method This allows all the current values of the array to be obtained for use by the method Example: Method Header: public static void swap(int[] x, int i, int j) In the body of Main: int[] list = 1,3,5,7,9; swap(list, 2, 4) sends the address of the array list to x, as well as the values of i and j Within the method x can reference 5 successive integers, the same as those in list. It is pointing to the same place. Therefore it can change that array. 14

15 Arrays and Methods(2) Passing an Array to a Method import java.util.scanner; public class ArraySwapper public static void swap(int[] x, int i, int j) int temp = x[i]; x[i] = x[j]; x[j] = temp; public static void main(string[] args) int [] list = 1,3,5,7,9; System.out.print("Before: "); for (int i=0; i<list.length; i++) System.out.print(list[i] + " "); swap(list,2,4); System.out.print("\nAfter:"); for (int i=0; i<list.length; i++) System.out.print(list[i] + " "); 15

16 Arrays and Methods (3) Passing an Array from a Method The value of the method can be a reference to an array created in the method If the method returns a reference then it must return the reference to an array of like type. However, you don t need to create a new array, just declare the reference variable. 16

17 Arrays and Methods (4) Passing an Array from a Method public class ArrayPassing public static double[] returnarray( ) double[] x; x = new double[3]; // Create an array of 3 elements x[0] = 2.3; x[1] = 3.4; x[2] = 4.5; return( x ); // Return the **reference** (location) of the array public static void main (String[] args) double [ ] a; a = returnarray(); for (int i=0; i < 3; i++) System.out.println(a[i]); 17

18 Using Arrays (1) Populating an Array public class ArrayDemo public static void main(string[] args) int[] anarray; // DECLARE a reference for an array of integers anarray = new int[10]; // CREATE an array of integers // assign a value to each array element for (int i = 0; i < anarray.length; i++) anarray[i] = i; // print a value from each array element for (int i = 0; i < anarray.length; i++) //anarray.length is variable equal to the size of the array System.out.print(anArray[i] + " "); System.out.println(); 18

19 Using Arrays (2) Populating an Array with a RunTime Array Length import java.util.*; public class ArrayDemo2 public static void main(string[] args) int size; int[] anarray; // DECLARE a reference for an array of integers Scanner keyboard = new Scanner(System.in); System.out.print("Input size of the array"); size= keyboard.nextint(); anarray = new int[size]; // CREATE an array of integers // assign a value to each array element for (int i = 0; i < anarray.length; i++) anarray[i] = i; // print a value from each array element for (int i = 0; i < anarray.length; i++) //anarray.length is variable equal to the size of the array System.out.print(anArray[i] + " "); System.out.println(); Deciding the size of the array in real-time allows the program to be more efficient and flexible it is data driven rather than hard-coded 19

20 Using Arrays (3) Finding The Maximum Number in an Array import java.util.*; public class ArrayMax public static void main(string[] args) int size, max_value; int[] anarray; // DECLARE an array of integers Scanner keyboard = new Scanner(System.in); System.out.print("Input size of the array: "); size= keyboard.nextint(); anarray = new int[size]; // CREATE an array of integers dynamically //read in an array for (int i=0; i < anarray.length; i++) System.out.println("Enter integer value for anarray(" +i +")"); anarray[i] = keyboard.nextint(); max_value= anarray[0]; for (int i = 1; i < anarray.length; i++) if (anarray[i] > max_value) max_value = anarray[i]; // print the maximum System.out.print("The maximum value of the array is: " +max_value); Now write a program to find the minimum value in an array. Then write a program that sums the numbers in an array 20

21 Using Arrays (4) Finding The Average of the Numbers in an Array import java.util.*; public class ArrayAverage public static void main(string[] args) int size, sum; long average; int[] anarray; // DECLARE an array of integers Scanner keyboard = new Scanner(System.in); System.out.print("Input size of the array: "); size= keyboard.nextint(); anarray = new int[size]; // CREATE an array of integers dynamically //read in an array for (int i=0; i < anarray.length; i++) System.out.println("Enter integer value for anarray(" +i +")"); anarray[i] = keyboard.nextint(); sum= 0; for (int i = 0; i < anarray.length; i++) sum = sum + anarray[i]; average = Math.round((double)(sum)/anArray.length); System.out.print("The average value of the array is: " +average); 21

22 Using Arrays (5) Sorting import java.util.*; public class ArraySorter public static void main(string []args) int size, swap; Scanner in = new Scanner(System.in); System.out.println("Input number of integers to sort"); size = in.nextint(); int array[] = new int[size]; System.out.println("Enter " + size + " integers"); for (int c = 0; c < size; c++) array[c] = in.nextint(); for (int c = 0; c < ( size - 1 ); c++) for (int d = 0; d < size - c - 1; d++) if (array[d] > array[d+1]) /* For descending order use < */ swap = array[d]; array[d] = array[d+1]; array[d+1] = swap; System.out.println("Sorted list of numbers"); for (int k = 0; k < size; k++) System.out.println(array[k]); 22

23 Using Arrays (6) - How Does the Insertion Method Work Assume the list is array[0] =15 array[1] = 14 array[2] = 13 array[3] = 12 after first round we have after second round after third round c d array[d] array[d+1] swap

24 Using Arrays (7) Search Linear Search Linear search is a method for searching one by one through a list until you find a match It is somewhat laborious For larger lists it becomes very inefficient Review ArrayLinearSearch.java for example Binary Search Requires that the list is ordered you can order the list first Simply keep dividing the list in half until you find the number Review ArrayBinarySearch.java 24

25 Two-Dimensional Arrays A two dimensional array is like a table or a matrix It has rows and columns In java, both the rows and columns are indexed starting at zero A two-dimensional array is actually an array of arrays As with one-dimensional arrays all values of the array must be of the same type The reference is always first by row and then column - array [row][column] Array [0][0] Array [0][1] Array [0][2] Array [0][3] Array [1][0] Array [1][1] Array [1][2] Array [1][3] Array [2][0] Array [2][1] Array [2][2] Array [2][3] Array [3][0] Array [3][1] Array [3][2] Array [3][3] Array [4][0] Array [4][1] Array [4][2] Array [4][3] 25

26 Declaring Two-Dimensional Arrays (1) Both the two-step and one step methods are available Two-steps: int[][] table; table = new int[2][3] One step: int[][] table = new int[2][3] It can be processed by row or by column Either way it looks like this, with all values initialized to 0:

27 Declaring Two-Dimensional Arrays (2) You can also explicitly declare a matrix by rows: int[][] gradetable = 99, 42, 74, 83, 100, 90, 91, 72, 88, 95, 88, 61, 74, 89, 96, 61, 89, 82, 98, 93, 93, 73, 75, 78, 99, 50, 65, 92, 87, 94, 43, 98, 78, 56, 99 Using this method you can create rows with uneven numbers of entries (advanced subject) row Col

28 Simple Example of a Useful Table Student Week The table has 7 rows and 5 columns the headers are not part of this table 28

29 Finding the Number of Rows and Columns of Arrays With Unequal Length The length of a two-dimensional array is its number of rows Array.length The number of columns in a row is Array[row].length In matrix below: Array.length = 5 Array[0].length = 4; Array[1].length = 3; Array[2].length = 4; Array[3].length = 2; Array[4].length = 4; Array [0][0] Array [0][1] Array [0][2] Array [0][3] Array [1][0] Array [1][1] Array [1][2] Array [2][0] Array [2][1] Array [2][2] Array [2][3] Array [3][0] Array [3][1] Array [4][0] Array [4][1] Array [4][2] Array [4][3] 29

30 Declaring An Array With Unequal Column Entries int [][] array = new int [4][]; array[0] = new int[5]; array[1] = new int[1]; array[2] = new int[1]; array[3] = new int[4]; Remember We are declaring an Array of Arrays 30

31 Declaring Two-Dimensional Arrays With Uneven Numbers of Columns during Population You can also explicitly declare a matrix by rows: int[][] gradetable = 99, 42, 74, 90, 91, 72, 88, 95, 88, 61, 89, 82, 98, 93, 73, 75, 78, 99, 50, 65, 92, 87, 94, 43, 98 Using this method you can create rows with uneven numbers of entries (advanced subject) Table.length = 7 Table[0].length = 3 Table[1].length = 5 Table[2].length = 1 Table[3].length = 4 Table[4].length = 5 Table[5].length = 5 Table[6].length = 2 row Col

32 Printing a Two-Dimensional Array class ArrayPrint2D public static void main( String[] args ) // declare and construct a 2D array int[][] myarray = 1, 9, 4, 6, 0, 2,4,5, 0, 1, 2, 3 ; // print out the array for ( int row=0; row < myarray.length; row++ ) System.out.print("Row " + row + ": "); for ( int col=0; col < myarray[row].length; col++ ) System.out.print( myarray[row][col] + " "); System.out.println(); 32

33 Programming Exercises Class (1) Exercise 1 Array Data Write two methods that read data from the console and store the data in an array: a. The method int readdata(int[] x) reads a list of at most 100 integers into the array x. A sentinel, -999, terminates the list. The method returns the size of the list. b. The method int[] readdata reads and returns a list of integers. The list is preceded by the number of the items in the list. For example, the data indicates that there are six items in the list. The leading 6 is not included in the list. Test both these methods within a single program that includes a method: void printlist(int [] x, int n) that displays x(0) through x(n-1) 33

34 Programming Exercises Class (2) Exercise 14 Max Sort Implement a method void maxsort(int[] x, int size) // that sorts the partially filled array x. The method maxsort( ) first determines the largest value in x and swaps that value with x[size-1]; then maxsort( ) finds the next largest value and swaps that value with x[size- 2], and so on. Include an auxiliary method int max(int[] x, int i) that returns the index of the largest element between x[0] and x[i] inclusive. Test your methods in a program. 34

35 Programming Exercises Lab (1) Exercise 9 Largest and Smallest Design a method that determines the largest and smallest values stored in an integer array x. Your method should return these values in an array of length 2. Use the following algorithms: Initialize variables currentbig and currentsmall to the larger and smaller values of x[0] and x[1]. Process the rest of the list two elements at a time. Compare the larger of the two elements to currentbig and replace currentbig if necessary. Compare the smaller of the two elements to currentsmall and replace currentsmall if necessary. Test your method in a program and include a method that reads a list, terminated by -999, into an array. 35

36 Programming Exercises Lab (2) Exercise 15 Selection Sort Implement a method void selectionsort(int[ ] x, int size) // (size <= x.length) that sorts the partially filled array x. The method selectionsort( ) first determines the smallest value in x and swaps that value with x[0]; then selectionsort( ) finds the next smallest value and swaps that with x[1] and so on. Include an auxiliary method int min(int[ ] x, int i) that returns the index of the smallest element between x[i] and x[size-1], inclusive. Test your methods in a program. 36

Arrays and Lists CSC 121 Fall 2015 Howard Rosenthal

Arrays and Lists CSC 121 Fall 2015 Howard Rosenthal Arrays and Lists CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand what an array is Understand how to declare arrays Understand what reference variables are Understand how to pass arrays to methods

More information

Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal

Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand what an array is Understand how to declare arrays Understand what reference variables are Understand how to pass arrays to methods

More information

Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal

Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Review what an array is Review how to declare arrays Review what reference variables are Review how to pass arrays to methods Review

More information

Array. Lecture 12. Based on Slides of Dr. Norazah Yusof

Array. Lecture 12. Based on Slides of Dr. Norazah Yusof Array Lecture 12 Based on Slides of Dr. Norazah Yusof 1 Introducing Arrays Array is a data structure that represents a collection of the same types of data. In Java, array is an object that can store a

More information

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

More information

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

More information

Last Class. While loops Infinite loops Loop counters Iterations

Last Class. While loops Infinite loops Loop counters Iterations Last Class While loops Infinite loops Loop counters Iterations public class January31{ public static void main(string[] args) { while (true) { forloops(); if (checkclassunderstands() ) { break; } teacharrays();

More information

Arrays. Eng. Mohammed Abdualal

Arrays. Eng. Mohammed Abdualal Islamic University of Gaza Faculty of Engineering Computer Engineering Department Computer Programming Lab (ECOM 2114) Created by Eng: Mohammed Alokshiya Modified by Eng: Mohammed Abdualal Lab 9 Arrays

More information

Declaring Array Variable

Declaring Array Variable 5. Arrays Sisoft Technologies Pvt Ltd SRC E7, Shipra Riviera Bazar, Gyan Khand-3, Indirapuram, Ghaziabad Website: www.sisoft.in Email:info@sisoft.in Phone: +91-9999-283-283 Array Arrays are used typically

More information

Object Oriented Programming. Java-Lecture 6 - Arrays

Object Oriented Programming. Java-Lecture 6 - Arrays Object Oriented Programming Java-Lecture 6 - Arrays Arrays Arrays are data structures consisting of related data items of the same type In Java arrays are objects -> they are considered reference types

More information

Fundamentals of Programming Data Types & Methods

Fundamentals of Programming Data Types & Methods Fundamentals of Programming Data Types & Methods By Budditha Hettige Overview Summary (Previous Lesson) Java Data types Default values Variables Input data from keyboard Display results Methods Operators

More information

Methods CSC 121 Fall 2016 Howard Rosenthal

Methods CSC 121 Fall 2016 Howard Rosenthal Methods CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand what a method is in Java Understand Java s Math Class and how to use it Learn the syntax of method construction Learn both void methods

More information

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

CS 152: Data Structures with Java Hello World with the IntelliJ IDE CS 152: Data Structures with Java Hello World with the IntelliJ IDE Instructor: Joel Castellanos e-mail: joel.unm.edu Web: http://cs.unm.edu/~joel/ Office: Electrical and Computer Engineering building

More information

Repetition CSC 121 Fall 2014 Howard Rosenthal

Repetition CSC 121 Fall 2014 Howard Rosenthal Repetition CSC 121 Fall 2014 Howard Rosenthal Lesson Goals Learn the following three repetition methods, their similarities and differences, and how to avoid common errors when using them: while do-while

More information

Methods CSC 121 Spring 2017 Howard Rosenthal

Methods CSC 121 Spring 2017 Howard Rosenthal Methods CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Understand what a method is in Java Understand Java s Math Class and how to use it Learn the syntax of method construction Learn both void methods

More information

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Repe$$on CSC 121 Fall 2015 Howard Rosenthal Repe$$on CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Learn the following three repetition methods, their similarities and differences, and how to avoid common errors when using them: while do-while

More information

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved 1 Thus far, you have used one-dimensional arrays to model linear collections of elements. You can use a two-dimensional array to represent a matrix or a table. For example, the following table that describes

More information

Array. Array Declaration:

Array. Array Declaration: Array Arrays are continuous memory locations having fixed size. Where we require storing multiple data elements under single name, there we can use arrays. Arrays are homogenous in nature. It means and

More information

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette COMP 250: Java Programming I Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette Variables and types [Downey Ch 2] Variable: temporary storage location in memory.

More information

Chapter 8 Multi-Dimensional Arrays

Chapter 8 Multi-Dimensional Arrays Chapter 8 Multi-Dimensional Arrays 1 1-Dimentional and 2-Dimentional Arrays In the previous chapter we used 1-dimensional arrays to model linear collections of elements. myarray: 6 4 1 9 7 3 2 8 Now think

More information

Exam 2. CSC 121 MW Class. Lecturer: Howard Rosenthal. April 26, 2017

Exam 2. CSC 121 MW Class. Lecturer: Howard Rosenthal. April 26, 2017 Your Name: Exam 2. CSC 121 MW Class Lecturer: Howard Rosenthal April 26, 2017 The following questions (or parts of questions) in numbers 1-7 are all worth 3 points each. 1. Answer the following as true

More information

It is a constructor and is called using the new statement, for example, MyStuff m = new MyStuff();

It is a constructor and is called using the new statement, for example, MyStuff m = new MyStuff(); COSC 117 Exam 3 Key Fall 2012 Part 1: Definitions & Short Answer (3 Points Each) 1. A method in a class that has no return type and the same name as the class is called what? How is this type of method

More information

1 Short Answer (10 Points Each)

1 Short Answer (10 Points Each) Name: Write all of your responses on these exam pages. 1 Short Answer (10 Points Each) 1. What is the difference between a compiler and an interpreter? Also, discuss how Java accomplishes this task. 2.

More information

1. What is the difference between a compiler and an interpreter? Also, discuss Java s method.

1. What is the difference between a compiler and an interpreter? Also, discuss Java s method. Name: Write all of your responses on these exam pages. 1 Short Answer (5 Points Each) 1. What is the difference between a compiler and an interpreter? Also, discuss Java s method. 2. Java is a platform-independent

More information

Fall 2017 CISC124 9/16/2017

Fall 2017 CISC124 9/16/2017 CISC124 Labs start this week in JEFF 155: Meet your TA. Check out the course web site, if you have not already done so. Watch lecture videos if you need to review anything we have already done. Problems

More information

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Repe$$on CSC 121 Spring 2017 Howard Rosenthal Repe$$on CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Learn the following three repetition structures in Java, their syntax, their similarities and differences, and how to avoid common errors when

More information

Variables and Assignments CSC 121 Spring 2017 Howard Rosenthal

Variables and Assignments CSC 121 Spring 2017 Howard Rosenthal Variables and Assignments CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Understand variables Understand how to declare and use variables in Java Programs Learn how to formulate assignment statements

More information

Computer Science & Engineering 150A Problem Solving Using Computers

Computer Science & Engineering 150A Problem Solving Using Computers Computer Science & Engineering 150A Problem Solving Using Computers Lecture 06 - Stephen Scott Adapted from Christopher M. Bourke 1 / 30 Fall 2009 Chapter 8 8.1 Declaring and 8.2 Array Subscripts 8.3 Using

More information

Variables and Assignments CSC 121 Fall 2015 Howard Rosenthal

Variables and Assignments CSC 121 Fall 2015 Howard Rosenthal Variables and Assignments CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand variables Understand how to declare and use variables in Java Programs Learn how to formulate assignment statements

More information

Last Class. More on loops break continue A bit on arrays

Last Class. More on loops break continue A bit on arrays Last Class More on loops break continue A bit on arrays public class February2{ public static void main(string[] args) { String[] allsubjects = { ReviewArray, Example + arrays, obo errors, 2darrays };

More information

Exam 2. CSC 121 MW Class. Lecturer: Howard Rosenthal. April 25, 2016

Exam 2. CSC 121 MW Class. Lecturer: Howard Rosenthal. April 25, 2016 Your Name: Exam 2. CSC 121 MW Class Lecturer: Howard Rosenthal April 25, 2016 The following questions (or parts of questions) in numbers 1-7 are all worth 3 points each. 1. Answer the following as true

More information

Chapter 7 Multidimensional Arrays. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Chapter 7 Multidimensional Arrays. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. Chapter 7 Multidimensional Arrays rights reserved. 1 Motivations Thus far, you have used one-dimensional arrays to model linear collections of elements. You can use a two-dimensional array to represent

More information

Example: Computing prime numbers

Example: Computing prime numbers Example: Computing prime numbers -Write a program that lists all of the prime numbers from 1 to 10,000. Remember a prime number is a # that is divisible only by 1 and itself Suggestion: It probably will

More information

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Arrays

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Arrays WIT COMP1000 Arrays Arrays An array is a list of variables of the same type, that represents a set of related values For example, say you need to keep track of the cost of 1000 items You could declare

More information

St. Edmund Preparatory High School Brooklyn, NY

St. Edmund Preparatory High School Brooklyn, NY AP Computer Science Mr. A. Pinnavaia Summer Assignment St. Edmund Preparatory High School Name: I know it has been about 7 months since you last thought about programming. It s ok. I wouldn t want to think

More information

Arrays. Chapter 7 (Done right after 4 arrays and loops go together, especially for loops)

Arrays. Chapter 7 (Done right after 4 arrays and loops go together, especially for loops) Arrays Chapter 7 (Done right after 4 arrays and loops go together, especially for loops) Object Quick Primer A large subset of Java s features are for OOP Object- Oriented Programming We ll get to that

More information

An Introduction To Writing Your Own Classes CSC 123 Fall 2018 Howard Rosenthal

An Introduction To Writing Your Own Classes CSC 123 Fall 2018 Howard Rosenthal An Introduction To Writing Your Own Classes CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Understand Object Oriented Programming The Syntax of Class Definitions Constructors this Object Oriented "Hello

More information

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15 Table of Contents 1 INTRODUCTION... 1 2 IF... 1 2.1 BOOLEAN EXPRESSIONS... 3 2.2 BLOCKS... 3 2.3 IF-ELSE... 4 2.4 NESTING... 5 3 SWITCH (SOMETIMES KNOWN AS CASE )... 6 3.1 A BIT ABOUT BREAK... 7 4 CONDITIONAL

More information

Java Arrays. What could go wrong here? Motivation. Array Definition 9/28/18. Mohammad Ghafari

Java Arrays. What could go wrong here? Motivation. Array Definition 9/28/18. Mohammad Ghafari 9/28/8 Java Arrays What could go wrong here? int table[][] = new int[2][]; // some code int sum = ; for (int i = ; i < 2; i++) for (int j = ; j < ; j++) int value = table[i][j]; sum += value; Mohammad

More information

1 Short Answer (10 Points Each)

1 Short Answer (10 Points Each) 1 Short Answer (10 Points Each) 1. For the following one-dimensional array, show the final array state after each pass of the three sorting algorithms. That is, after each iteration of the outside loop

More information

Arrays. Weather Problem Array Declaration Accessing Elements Arrays and for Loops Array length field Quick Array Initialization Array Traversals

Arrays. Weather Problem Array Declaration Accessing Elements Arrays and for Loops Array length field Quick Array Initialization Array Traversals Arrays Weather Problem Array Declaration Accessing Elements Arrays and for Loops Array length field Quick Array Initialization Array Traversals Can we solve this problem? Consider the following program

More information

Array. Prepared By - Rifat Shahriyar

Array. Prepared By - Rifat Shahriyar Java More Details Array 2 Arrays A group of variables containing values that all have the same type Arrays are fixed length entities In Java, arrays are objects, so they are considered reference types

More information

COMP-202B - Introduction to Computing I (Winter 2011) - All Sections Example Questions for In-Class Quiz

COMP-202B - Introduction to Computing I (Winter 2011) - All Sections Example Questions for In-Class Quiz COMP-202B - Introduction to Computing I (Winter 2011) - All Sections Example Questions for In-Class Quiz The in-class quiz is intended to give you a taste of the midterm, give you some early feedback about

More information

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types COMP-202 Unit 6: Arrays Introduction (1) Suppose you want to write a program that asks the user to enter the numeric final grades of 350 COMP-202

More information

Give one example where you might wish to use a three dimensional array

Give one example where you might wish to use a three dimensional array CS 110: INTRODUCTION TO COMPUTER SCIENCE SAMPLE TEST 3 TIME ALLOWED: 60 MINUTES Student s Name: MAXIMUM MARK 100 NOTE: Unless otherwise stated, the questions are with reference to the Java Programming

More information

Lesson 7 Part 2 Flags

Lesson 7 Part 2 Flags Lesson 7 Part 2 Flags A Flag is a boolean variable that signals when some condition exists in a program. When a flag is set to true, it means some condition exists When a flag is set to false, it means

More information

CEN 414 Java Programming

CEN 414 Java Programming CEN 414 Java Programming Instructor: H. Esin ÜNAL SPRING 2017 Slides are modified from original slides of Y. Daniel Liang WEEK 2 ELEMENTARY PROGRAMMING 2 Computing the Area of a Circle public class ComputeArea

More information

Arrays. Defining arrays, declaration and initialization of arrays. Designed by Parul Khurana, LIECA.

Arrays. Defining arrays, declaration and initialization of arrays. Designed by Parul Khurana, LIECA. Arrays Defining arrays, declaration and initialization of arrays Introduction Many applications require the processing of multiple data items that have common characteristics (e.g., a set of numerical

More information

System.out.print("Enter sales for salesperson " + i + ": "); sales[i] = scan.nextint();

System.out.print(Enter sales for salesperson  + i + : ); sales[i] = scan.nextint(); Tracking Sales File Sales.java contains a Java program that prompts for and reads in the sales for each of 5 salespeople in a company. It then prints out the id and amount of sales for each salesperson

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Programming with Java

Programming with Java Programming with Java Data Types & Input Statement Lecture 04 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives q By the end of this lecture you should be able to : ü Know rules

More information

Lecture 17. Instructor: Craig Duckett. Passing & Returning Arrays

Lecture 17. Instructor: Craig Duckett. Passing & Returning Arrays Lecture 17 Instructor: Craig Duckett Passing & Returning Arrays Assignment Dates (By Due Date) Assignment 1 (LECTURE 5) GRADED! Section 1: Monday, January 22 nd Assignment 2 (LECTURE 8) GRADED! Section

More information

Lecture #8-10 Arrays

Lecture #8-10 Arrays Lecture #8-10 Arrays 1. Array data structure designed to store a fixed-size sequential collection of elements of the same type collection of variables of the same type 2. Array Declarations Creates a Storage

More information

Computer programming Code exercises [1D Array]

Computer programming Code exercises [1D Array] Computer programming-140111014 Code exercises [1D Array] Ex#1: //Program to read five numbers, from user. public class ArrayInput public static void main(string[] args) Scanner input = new Scanner(System.in);

More information

Computer Science is...

Computer Science is... Computer Science is... Machine Learning Machine learning is the study of computer algorithms that improve automatically through experience. Example: develop adaptive strategies for the control of epileptic

More information

Arrays. Chapter 6. Array Basics Arrays in Classes and Methods Programming with Arrays and Classes Sorting Arrays Multidimensional Arrays

Arrays. Chapter 6. Array Basics Arrays in Classes and Methods Programming with Arrays and Classes Sorting Arrays Multidimensional Arrays Chapter 6 Arrays Array Basics Arrays in Classes and Methods Programming with Arrays and Classes Sorting Arrays Multidimensional Arrays Chapter 6 Java: an Introduction to Computer Science & Programming

More information

Over and Over Again GEEN163

Over and Over Again GEEN163 Over and Over Again GEEN163 There is no harm in repeating a good thing. Plato Homework A programming assignment has been posted on Blackboard You have to convert three flowcharts into programs Upload the

More information

More Arrays. Last updated 2/6/19

More Arrays. Last updated 2/6/19 More Last updated 2/6/19 2 Dimensional Consider a table 1 2 3 4 5 6 5 4 3 2 12 11 13 14 15 19 17 16 3 1 4 rows x 5 columns 2 tj 2 Dimensional Consider a table 1 2 3 4 5 6 5 4 3 2 12 11 13 14 15 19 17 16

More information

H212 Introduction to Software Systems Honors

H212 Introduction to Software Systems Honors Introduction to Software Systems Honors Lecture #04: Fall 2015 1/20 Office hours Monday, Wednesday: 10:15 am to 12:00 noon Tuesday, Thursday: 2:00 to 3:45 pm Office: Lindley Hall, Room 401C 2/20 Printing

More information

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I AL GHURAIR UNIVERSITY College of Computing CSC 209 JAVA I week 2- Arithmetic and Decision Making: Equality and Relational Operators Objectives: To use arithmetic operators. The precedence of arithmetic

More information

Exam 2. CSC 121 TTH Class. Lecturer: Howard Rosenthal. April 26, 2016

Exam 2. CSC 121 TTH Class. Lecturer: Howard Rosenthal. April 26, 2016 Your Name: Exam 2. CSC 121 TTH Class Lecturer: Howard Rosenthal April 26, 2016 The following questions (or parts of questions) in numbers 1-7 are all worth 3 points each. 1. Answer the following as true

More information

BlueJ Demo. Topic 1: Basic Java. 1. Sequencing. Features of Structured Programming Languages

BlueJ Demo. Topic 1: Basic Java. 1. Sequencing. Features of Structured Programming Languages Topic 1: Basic Java Plan: this topic through next Friday (5 lectures) Required reading on web site I will not spell out all the details in lecture! BlueJ Demo BlueJ = Java IDE (Interactive Development

More information

University of Cape Town ~ Department of Computer Science. Computer Science 1015F ~ 2007

University of Cape Town ~ Department of Computer Science. Computer Science 1015F ~ 2007 Name: Please fill in your Student Number and Name. Student Number : Student Number: University of Cape Town ~ Department of Computer Science Computer Science 1015F ~ 2007 Final Examination Question Max

More information

13 th Windsor Regional Secondary School Computer Programming Competition

13 th Windsor Regional Secondary School Computer Programming Competition SCHOOL OF COMPUTER SCIENCE 13 th Windsor Regional Secondary School Computer Programming Competition Hosted by The School of Computer Science, University of Windsor WORKSHOP I [ Overview of the Java/Eclipse

More information

Last Class. Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it

Last Class. Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it Last Class Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it public class February4{ public static void main(string[] args) { String[]

More information

Java Coding 3. Over & over again!

Java Coding 3. Over & over again! Java Coding 3 Over & over again! Repetition Java repetition statements while (condition) statement; do statement; while (condition); where for ( init; condition; update) statement; statement is any Java

More information

Chapter 7: Arrays and the ArrayList Class

Chapter 7: Arrays and the ArrayList Class Chapter 7: Arrays and the ArrayList Class Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis Chapter Topics Chapter 7 discusses the following main topics: Introduction

More information

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods Islamic University of Gaza Faculty of Engineering Computer Engineering Dept. Computer Programming Lab (ECOM 2114) ABSTRACT In this Lab you will learn to define and invoke void and return java methods JAVA

More information

2. Each element of an array is accessed by a number known as a(n) a. a. subscript b. size declarator c. address d. specifier

2. Each element of an array is accessed by a number known as a(n) a. a. subscript b. size declarator c. address d. specifier Lesson 4 Arrays and Lists Review CSC 123 Fall 2018 Answer Sheet Short Answers 1. In an array declaration, this indicates the number of elements that the array will have. b a. subscript b. size declarator

More information

Arrays and the TOPICS CHAPTER 8. CONCEPT: An array can hold multiple values of the same data type simultaneously.

Arrays and the TOPICS CHAPTER 8. CONCEPT: An array can hold multiple values of the same data type simultaneously. CHAPTER 8 Arrays and the ArrayList Class TOPICS 8.1 Introduction to Arrays 8.2 Processing Array Elements 8.3 Passing Arrays As Arguments to Methods 8.4 Some Useful Array Algorithms and Operations 8.5 Returning

More information

Introduction to Software Development (ISD) Week 3

Introduction to Software Development (ISD) Week 3 Introduction to Software Development (ISD) Week 3 Autumn term 2012 Aims of Week 3 To learn about while, for, and do loops To understand and use nested loops To implement programs that read and process

More information

Chapter 2: Basic Elements of Java

Chapter 2: Basic Elements of Java Chapter 2: Basic Elements of Java TRUE/FALSE 1. The pair of characters // is used for single line comments. ANS: T PTS: 1 REF: 29 2. The == characters are a special symbol in Java. ANS: T PTS: 1 REF: 30

More information

CIS 1068 Program Design and Abstraction Spring2016 Midterm Exam 1. Name SOLUTION

CIS 1068 Program Design and Abstraction Spring2016 Midterm Exam 1. Name SOLUTION CIS 1068 Program Design and Abstraction Spring2016 Midterm Exam 1 Name SOLUTION Page Points Score 2 15 3 8 4 18 5 10 6 7 7 7 8 14 9 11 10 10 Total 100 1 P age 1. Program Traces (41 points, 50 minutes)

More information

Input. Scanner keyboard = new Scanner(System.in); String name;

Input. Scanner keyboard = new Scanner(System.in); String name; Reading Resource Input Read chapter 4 (Variables and Constants) in the textbook A Guide to Programming in Java, pages 77 to 82. Key Concepts A stream is a data channel to or from the operating system.

More information

Arrays. Chapter 6. Array Basics Arrays in Classes and Methods Programming with Arrays and Classes Sorting Arrays Multidimensional Arrays

Arrays. Chapter 6. Array Basics Arrays in Classes and Methods Programming with Arrays and Classes Sorting Arrays Multidimensional Arrays Chapter 6 Arrays Array Basics Arrays in Classes and Methods Programming with Arrays and Classes Sorting Arrays Multidimensional Arrays Chapter 6 Java: an Introduction to Computer Science & Programming

More information

Getting started with Java

Getting started with Java Getting started with Java Magic Lines public class MagicLines { public static void main(string[] args) { } } Comments Comments are lines in your code that get ignored during execution. Good for leaving

More information

CS 101 Fall 2006 Midterm 1 Name: ID:

CS 101 Fall 2006 Midterm 1 Name:  ID: You only need to write your name and e-mail ID on the first page. This exam is CLOSED text book, closed-notes, closed-calculator, closed-neighbor, etc. Questions are worth different amounts, so be sure

More information

Arrays and functions Multidimensional arrays Sorting and algorithm efficiency

Arrays and functions Multidimensional arrays Sorting and algorithm efficiency Introduction Fundamentals Declaring arrays Indexing arrays Initializing arrays Arrays and functions Multidimensional arrays Sorting and algorithm efficiency An array is a sequence of values of the same

More information

Program Control Flow

Program Control Flow Lecture slides for: Chapter 3 Program Control Flow Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2

More information

Program Control Flow

Program Control Flow Lecture slides for: Chapter 3 Program Control Flow Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2

More information

H212 Introduction to Software Systems Honors

H212 Introduction to Software Systems Honors Introduction to Software Systems Honors Lecture #07: September 21, 2015 1/30 We explained last time that an array is an ordered list of values. Each value is stored at a specific, numbered position in

More information

Software Practice 1 Basic Grammar

Software Practice 1 Basic Grammar Software Practice 1 Basic Grammar Basic Syntax Data Type Loop Control Making Decision Prof. Joonwon Lee T.A. Jaehyun Song Jongseok Kim (42) T.A. Sujin Oh Junseong Lee (43) 1 2 Java Program //package details

More information

Software Practice 1 - Basic Grammar Basic Syntax Data Type Loop Control Making Decision

Software Practice 1 - Basic Grammar Basic Syntax Data Type Loop Control Making Decision Software Practice 1 - Basic Grammar Basic Syntax Data Type Loop Control Making Decision Prof. Hwansoo Han T.A. Minseop Jeong T.A. Wonseok Choi 1 Java Program //package details public class ClassName {

More information

The ArrayList class CSC 123 Fall 2018 Howard Rosenthal

The ArrayList class CSC 123 Fall 2018 Howard Rosenthal The ArrayList class CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Describe the ArrayList class Discuss important methods of this class Describe how it can be used in modeling Much of the information

More information

Chapter 6. Arrays. Array Basics Arrays in Classes and Methods Programming with Arrays and Classes Sorting Arrays Multidimensional Arrays

Chapter 6. Arrays. Array Basics Arrays in Classes and Methods Programming with Arrays and Classes Sorting Arrays Multidimensional Arrays Chapter 6 Arrays Array Basics Arrays in Classes and Methods Programming with Arrays and Classes Sorting Arrays Multidimensional Arrays Chapter 6 Java: an Introduction to Computer Science & Programming

More information

Darrell Bethea May 25, 2011

Darrell Bethea May 25, 2011 Darrell Bethea May 25, 2011 Yesterdays slides updated Midterm on tomorrow in SN014 Closed books, no notes, no computer Program 3 due Tuesday 2 3 A whirlwind tour of almost everything we have covered so

More information

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2 CONTENTS: Compilation Data and Expressions COMP 202 More on Chapter 2 Programming Language Levels There are many programming language levels: machine language assembly language high-level language Java,

More information

Darrell Bethea May 10, MTWRF 9:45-11:15 AM Sitterson 011

Darrell Bethea May 10, MTWRF 9:45-11:15 AM Sitterson 011 Darrell Bethea May 10, 2011 MTWRF 9:45-11:15 AM Sitterson 011 1 Office hours: MW 1-2 PM If you still cannot make it to either office hour, email me to set up an appointment if you need help with an assignment.

More information

Instructor: Eng.Omar Al-Nahal

Instructor: Eng.Omar Al-Nahal Faculty of Engineering & Information Technology Software Engineering Department Computer Science [2] Lab 6: Introduction in arrays Declaring and Creating Arrays Multidimensional Arrays Instructor: Eng.Omar

More information

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II 1 CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 1: Introduction Lecture Contents 2 Course info Why programming?? Why Java?? Write once, run anywhere!! Java basics Input/output Variables

More information

Chapter 6 SINGLE-DIMENSIONAL ARRAYS

Chapter 6 SINGLE-DIMENSIONAL ARRAYS Chapter 6 SINGLE-DIMENSIONAL ARRAYS Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk What is an Array? A single array variable can reference

More information

STUDENT LESSON A12 Iterations

STUDENT LESSON A12 Iterations STUDENT LESSON A12 Iterations Java Curriculum for AP Computer Science, Student Lesson A12 1 STUDENT LESSON A12 Iterations INTRODUCTION: Solving problems on a computer very often requires a repetition of

More information

Spring 2010 Java Programming

Spring 2010 Java Programming Java Programming: Guided Learning with Early Objects Chapter 7 - Objectives Learn about arrays Explore how to declare and manipulate data in arrays Learn about the instance variable length Understand the

More information

Arrays. Here is the generic syntax for an array declaration: type[] <var_name>; Here's an example: int[] numbers;

Arrays. Here is the generic syntax for an array declaration: type[] <var_name>; Here's an example: int[] numbers; Arrays What are they? An array is a data structure that holds a number of related variables. Thus, an array has a size which is the number of variables it can store. All of these variables must be of the

More information

ITI1120 Introduction to Computing I Exercise Workbook Fall 2012

ITI1120 Introduction to Computing I Exercise Workbook Fall 2012 ITI1120 Introduction to Computing I Exercise Workbook Fall 2012 1 Table of Contents 1 Introduction 3 2 Computer Programming Model 3 3 Pre-defined Algorithm Models 6 4 Summary of Program Structure, Algorithm

More information

CS 101 Spring 2007 Midterm 2 Name: ID:

CS 101 Spring 2007 Midterm 2 Name:  ID: You only need to write your name and e-mail ID on the first page. This exam is CLOSED text book, closed-notes, closed-calculator, closed-neighbor, etc. Questions are worth different amounts, so be sure

More information

4. Java language basics: Function. Minhaeng Lee

4. Java language basics: Function. Minhaeng Lee 4. Java language basics: Function Minhaeng Lee Review : loop Program print from 20 to 10 (reverse order) While/for Program print from 1, 3, 5, 7.. 21 (two interval) Make a condition that make true only

More information

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled Interpreted vs Compiled Python 1 Java Interpreted Easy to run and test Quicker prototyping Program runs slower Compiled Execution time faster Virtual Machine compiled code portable Java Compile > javac

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

Mr. Monroe s Guide to Mastering Java Syntax

Mr. Monroe s Guide to Mastering Java Syntax Mr. Monroe s Guide to Mastering Java Syntax Getting Started with Java 1. Download and install the official JDK (Java Development Kit). 2. Download an IDE (Integrated Development Environment), like BlueJ.

More information