New Concepts. Lab 7 Using Arrays, an Introduction

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

ECE 122. Engineering Problem Solving with Java

CS313D: ADVANCED PROGRAMMING LANGUAGE. Lecture 3: C# language basics II

2/3/2018 CS313D: ADVANCED PROGRAMMING LANGUAGE. Lecture 3: C# language basics II. Lecture Contents. C# basics. Methods Arrays. Dr. Amal Khalifa, Spr17

AP Computer Science A Summer Assignment 2017

Arrays and functions Multidimensional arrays Sorting and algorithm efficiency

EECS168 Exam 3 Review

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal

CS313D: ADVANCED PROGRAMMING LANGUAGE

Computer Science & Engineering 150A Problem Solving Using Computers

Expressions and Casting

Overview. Lab 5 Methods and Parameters

Introduction to Programming Using Java (98-388)

UNIT V Sub u P b ro r g o r g a r m a s

Chapter 4 Defining Classes I

COMSC-051 Java Programming Part 1. Part-Time Instructor: Joenil Mistal

Technical Section. Lab 4 while loops and for loops. A. while Loops or for loops

Arrays and Lists CSC 121 Fall 2015 Howard Rosenthal

ICOM 4015 Advanced Programming Laboratory. Chapter 1 Introduction to Eclipse, Java and JUnit

Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal

Expressions and Casting. Data Manipulation. Simple Program 11/5/2013

Programming Studio #9 ECE 190

B. Subject-specific skills B1. Problem solving skills: Supply the student with the ability to solve different problems related to the topics

A Java Execution Simulator

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016

Introduction to the Java Basics: Control Flow Statements

Arrays and Lists CSC 121 Fall 2014 Howard Rosenthal

Chapter 6 SINGLE-DIMENSIONAL ARRAYS

Principles of Computer Science

Chapter 3: Operators, Expressions and Type Conversion

Arrays. Eng. Mohammed Abdualal

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

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

Arrays. CSE 142, Summer 2002 Computer Programming 1.

G Programming Languages - Fall 2012

Summer Assignment for the School Year

Debugging [continued]

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

Chapter 9 Introduction to Arrays. Fundamentals of Java

Debugging [continued]

1 class Lecture2 { 2 3 "Elementray Programming" / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch.

What we will do today Explain and look at examples of. Programs that examine data. Data types. Topic 4. variables. expressions. assignment statements

Main concepts to be covered. Testing and Debugging. Code snippet of the day. Results. Testing Debugging Test automation Writing for maintainability

LAB 12: ARRAYS (ONE DIMINSION)

CS111: PROGRAMMING LANGUAGE II

COS 126 General Computer Science Spring Written Exam 1

Programming Exercise 7: Static Methods

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

UNIVERSITY OF WINDSOR Fall 2007 QUIZ # 2 Solution. Examiner : Ritu Chaturvedi Dated :November 27th, Student Name: Student Number:

Arrays. Inf1-OP. Arrays. Many Variables of the Same Type. Arrays 1. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein

QUIZ How do we implement run-time constants and. compile-time constants inside classes?

What goes inside when you declare a variable?

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

Inf1-OP. Arrays 1. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. February 26, School of Informatics

1.4 Arrays. A Foundation for Programming. Many Variables of the Same Type. Arrays. !!! any program you might want to write

Discover how to get up and running with the Java Development Environment and with the Eclipse IDE to create Java programs.

Recommended Design Techniques for ECE241 Project Franjo Plavec Department of Electrical and Computer Engineering University of Toronto

STUDENT LESSON A12 Iterations

Review! * follows a pointer to its value! & gets the address of a variable! Pearce, Summer 2010 UCB! ! int x = 1000; Pearce, Summer 2010 UCB!

Inf1-OOP. Arrays. Many Variables of the Same Type. Arrays Introduction to Arrays Arrays in Java Shuffling a Deck Multidimensional Arrays Summary/Admin

Figure 1: Network topology and link costs for DV routing

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows

Lab #10 Multi-dimensional Arrays

Agenda / Learning Objectives: 1. Map out a plan to study for mid-term Review the C++ operators up to logical operators. 3. Read about the tips

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

Programming overview

Inf1-OOP. Arrays 1. Perdita Stevens, adapting earlier version by Ewan Klein. January 11, School of Informatics

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

Programming in Visual Basic with Microsoft Visual Studio 2010

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

CS 231 Data Structures and Algorithms, Fall 2016

Arrays. Introduction to OOP with Java. Lecture 06: Introduction to OOP with Java - AKF Sep AbuKhleiF - 1

PROGRAMMING IN VISUAL BASIC WITH MICROSOFT VISUAL STUDIO Course: 10550A; Duration: 5 Days; Instructor-led

SYSC 2006 C Winter 2012

Two hours QUESTION PAPER MUST NOT BE REMOVED FROM THE EXAM ROOM UNIVERSITY OF MANCHESTER SCHOOL OF COMPUTER SCIENCE

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

CPSC 150 Laboratory Manual. Lab 1 Introduction to Program Creation

AP Computer Science Homework Set 1 Fundamentals

McGill University School of Computer Science COMP-202A Introduction to Computing 1

Title. Syntax. stata.com. function. void [ function ] declarations Declarations and types. declaration 1 fcnname(declaration 2 ) { declaration 3

Lab 8. An Introduction to Objects

Arrays and Pointers (part 1)

A Bad Idea Monday, April 16, :23 AM

Center for Computation & Louisiana State University -


Testing and Debugging

Computer Programming: C++

CS 230 Programming Languages


Project 1: Empirical Analysis of Algorithms

Object Oriented Programming. Java-Lecture 6 - Arrays

Introduction to Java & Fundamental Data Types

CITS1001 week 4 Grouping objects

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

Lecture 4: Outline. Arrays. I. Pointers II. III. Pointer arithmetic IV. Strings

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Transcription:

Lab 7 Using Arrays, an Introduction New Concepts Grading: This lab requires the use of the grading sheet for responses that must be checked by your instructor (marked as Question) AND the submission of some programs to WebCAT (marked as Lab). Be sure to have a copy of the grading sheet, acquire the appropriate signatures and submit the sheet to your instructor in addition to submitting the appropriate labs to WebCAT. Understanding how to manage large quantities of data is a critical requirement of designing software, and the most confusing part of it is the variety of choices available. Of these choices, arrays represent the most fundamental means of organizing, and are commonly available in most all programming languages. An array is just a table of values, where the entire table is referenced by a single name. The problem inherent in this is that once we start using one name to refer to a number of different values, we need an additional tool for accessing the individual values. In regards to the representation of these arrays, do not be concerned as to the orientation (horizontal or vertical) as it is irrelevant. Array x: Each element is referenced by using the array name followed by the position in brackets. Also note that the positions start with 0. Here x has 7 elements, positions 0..6. Array x:

x[0] x[1] x[2] x[3] x[4] x[5] x[6] Declaring an array: To allocate an array like this in java, assuming integer values are stored in the array, use int [] x = new int [7]; Technical Section Initializing / Placing data into an array: There are a number of ways to define values for an array. One of the simplest (and LEAST useful) is at the time of declaration: int [] x = { 3, 45, 17, 2, - 1, 44, 9}; Array x: 3 45 17 2-1 44 9 x[0] x[1] x[2] x[3] x[4] x[5] x[6] The most likely place where you will use this approach is for initialization when testing a program, because it provides a convenient way of defining a set of test values. We will use this approach here for that same reason. Most often, one changes the values one element at a time, similar to the following: x[5] = - 1; Array x: 3 45 17 2-1 - 1 9 x[0] x[1] x[2] x[3] x[4] x[5] x[6] In addition the use can be more diversified to include the arrays in more complicated ways. For example: x[2] = x[3];

Array x: 3 45 2 2-1 - 1 9 x[0] x[1] x[2] x[3] x[4] x[5] x[6] See if you can determine how the state of the array changes when executing: x[1] = x[x[0]];

Answer: Array x: 3 2 2 2-1 - 1 9 x[0] x[1] x[2] x[3] x[4] x[5] x[6] If this is confusing you, ask a student or your instructor for some help before going on. Now that you have a basic understanding of how arrays and indexing works, consider the following which illustrates a more typical way that arrays will be used in your programs. Frequently there is a need to access all of the values, to do something like set the values to zero, or find the average of the values in the array. Start with the simplest, setting all elements to zero. Once the array has been declared, one might think that the elements could be set to zero by x = 0; but this is not allowed. One must write a loop to repeatedly apply this same operation: for(int i = 0; i < x.length; i++){ } x[i] = 0; In truth, the arrays will be initialized to the value appropriate to the type (int, double, etc) without any explicit effort on your part. In contrast, primitive variables are not always initialized. This can be very confusing and is contrary to what happens in most programming languages, so it is suggested that arrays should be initialized by assignment as above. This part of the lab will investigate how variables and arrays are initialized. Load the sample java application arrays.java into a BlueJ project. Open the arrays.java source file and compile it. Now set a breakpoint in the samplemethod method on the line that prints Leaving!, and run the program.

The debugger shows some of the variables and not others. Double- click the line int y[]= in the debug window which will reveal the contents of the array y. Answer the following questions: Why is x missing? How did a get the values that are stored in it? What is different about the way a is initialized when compared to the way b is initialized? NOTE: This question is focusing on how arrays are initialized in contrast with the way that primitives (like a) are initialized. You want to be careful about assumptions that you make concerning how java initializes variables because it is not consistent. Bottom line is that you should make sure that you initialize variables yourself. Other programming languages may not initialize at all, so developing a habit of initializing memory with your own code will be more universally correct. Question 1 Show your instructor your responses and the values in the array y as revealed by the debugger.

Loops for manipulating an array: Note that there is a convenient property named length available with an array, and it is used in the loop below to print the values in the array. Frequently one uses loops to process array elements (illustrated here by printing them), and there are really three basic ways of iterating over the elements: 1. while loops 2. for loops 3. foreach loops In this part of the lab, you will investigate these loop strategies. First, consider the simple loop to print the elements in an array. while version: i = 0; while (i<x.length) } { System.out.println(x[i]); i++; for version: for (i=0; i<x.length; i++) { System.out.println(x[i]); } foreach version: for (double e : x) { System.out.println(e); } You can think of the foreach loop as a shorthand for a for loop. For example the example above is equivalent to the following code: double e = 0; for(int i=0; i < x.length; i++){ e = x[i];

} System.out.println(e); In the first two examples, the programmer is responsible to implement a counter ( i in this example) to indicate location of successive values. The first two loop types are basically identical and only differ in where the operations are placed in the syntax. They also represent a much more general and powerful way of iterating; i.e. they can do things a foreach loop can not. Nonetheless, a foreach loop provides a simple and effective way to iterate over the elements. Limitations of foreach: Be aware that one can only use foreach under the following restrictions: only to access, not change the elements o x[i]=3; only to move forward, o can not access in reverse only access every element o not every other element (odd positions etc) can not be used to do something like compare two arrays o x[i]>y[i]

Write a new java application named array2 which includes a simple main routine to use the following array int [] x = {3,45,17,2,- 1,44,9,23,67,2,- 6,- 23,- 100,12,5,1212}; and as space separated lists output the values in the array using a for loop output the values in the array using foreach output the values in reverse order using a while loop output the values in the odd number positions (1,3, ) using a for loop. output the average of the values using foreach Your output should be the following: 3 45 17 2-1 44 9 23 67 2-6 - 23-100 12 5 1212 3 45 17 2-1 44 9 23 67 2-6 - 23-100 12 5 1212 1212 5 12-100 - 23-6 2 67 23 9 44-1 2 17 45 3 45 2 44 23 2-23 12 1212 Show your code and the output to your instructor. Question 2

Writing methods with arrays: When using arrays as parameters, one should be mindful that when you pass arrays, changes to the formal parameters WILL change the actual parameters. This is not true of primitives (i.e. double and int). Consider the following example where the typical approach to swap two values looks like: temp = a; a = b; b = temp; Create a new class, ArrayExamples and define a method called swapints which is to take two integer parameters with a return type of void. Test this method from the main method. To show when, and where, the values are swapped you are to print out the values (a and b) three times: 1. In the calling method (main) before calling swapints 2. In Swap Ints after the values are swapped 3. In the calling method (main) after the call to swapints Now write a second method public void swapintarrays(int [] a, int [] b). This method is to swap ALL the values in the two array parameters. Using a for loop, this method must iterate over the elements of the arrays, swapping the corresponding i th elements as you go through the elements. In the loop body, use code similar to the swapints described above but replace a and b with a[i] and b[i]. The temp variable is not an array, it is still of type int. Submit the class ArrayExamples including the method public static void swapintarrays(int [] a, int [] b) to WebCAT for grading and verification that you have written the method correctly. Lab 7 A In the main method, create two arrays with values initialized in the declaration. Now test the method. If the method is working correctly the values originally in the first array should now be in the second array and vice versa. Print out the values in both arrays two times (as space separated lists like Question #2): 1. Before calling the method

2. After calling the method You SHOULD see the values swapped in the two arrays. If WebCAT graded the submission as successful, the only question is whether or not you are using it in the main routine as directed. Question 3 Show your instructor the code and explain the results of swapints and swapintarrays Programming Section Continue defining the following methods in the ArrayExamples class Write a method void replacelessthan(int []a, int b) that accepts an integer array and another integer. Iterate over the array and replace all numbers less than the number with the value of the second parameter. If passed the array int [] x = {3,45,17,2,- 1,44,9,23,67,2,- 6,- 23,- 100,12,5,1212}; and 12, x would be altered to contain { 12,45,17,12,12,44,12,23,67,12,12,12,12,12,12,1212} In main, test this method. Print the array before and after calling the method. Submit the ArrayExamples class with the public static void replacelessthan(int []a, int b) method to WebCAT for grading. Lab 7 B

Write a second version which is very similar but returns an array with the results, leaving the original array unaltered. int [] copyandreplacelessthan(int []a, int b) As before, test this method in main. Print both the original array and the returned array which the method, copyandreplacelessthan, returns. Since this method returns a value (an integer array), you need to catch the returned value in a local variable (of type int []) in the calling method (main). For example: Assuming you pass the array x to the method and use array y to catch the returned value. Print x before you call the method and then print both x and y after calling the method. This is typical of the kinds of design choices that you will make, choosing whether to send the results back to the caller by modifying the input (the former) or returning a modified copy (the latter). Submit the ArrayExamples class with the public static int [] copyandreplacelessthan(int []a, int b) method to WebCAT for grading. Lab 7 C

Student s Name ID Lab 7: Completion Table Question Completed Comments yes no 1 2 3 Instructor s signature Grade Question 1. Answer the following questions: Why is x missing? How did a get the values that are stored in it? What is confusing about the way a: is initialized when compared to the way b is initialized?