Slide 1 CS 170 Java Programming 1 Arrays and Loops Duration: 00:01:27 Advance mode: Auto

Similar documents
Slide 1 CS 170 Java Programming 1 Multidimensional Arrays Duration: 00:00:39 Advance mode: Auto

Slide 1 CS 170 Java Programming 1

Slide 1 CS 170 Java Programming 1 Testing Karel

Slide 1 Side Effects Duration: 00:00:53 Advance mode: Auto

Slide 1 CS 170 Java Programming 1 The while Loop Duration: 00:00:60 Advance mode: Auto

Express Yourself. What is Eclipse?

Slide 1 CS 170 Java Programming 1 Expressions Duration: 00:00:41 Advance mode: Auto

Slide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Advance mode: Auto

Slide 1 CS 170 Java Programming 1 More on Strings Duration: 00:00:47 Advance mode: Auto

Slide 1 CS 170 Java Programming 1 Real Numbers Duration: 00:00:54 Advance mode: Auto

Slide 1 CS 170 Java Programming 1 Loops, Jumps and Iterators Duration: 00:01:20 Advance mode: Auto

CS 170 Java Programming 1. Week 10: Loops and Arrays

Slide 1 CS 170 Java Programming 1 Duration: 00:00:49 Advance mode: Auto

Slide 1 Java Programming 1 Lecture 2D Java Mechanics Duration: 00:01:06 Advance mode: Auto

CS Homework 11 p. 1. CS Homework 11

Structured Programming

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #29 Arrays in C

Hi everyone. Starting this week I'm going to make a couple tweaks to how section is run. The first thing is that I'm going to go over all the slides

Express Yourself. Writing Your Own Classes

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Laboratory 5: Implementing Loops and Loop Control Strategies

MITOCW watch?v=0jljzrnhwoi

Express Yourself. The Great Divide

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Post Experiment Interview Questions

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

Warmup : Name that tune!

Homework 09. Collecting Beepers

A PROGRAM IS A SEQUENCE of instructions that a computer can execute to

Grouping Objects. Primitive Arrays and Iteration. Produced by: Dr. Siobhán Drohan. Department of Computing and Mathematics

Week 3: Objects, Input and Processing

So on the survey, someone mentioned they wanted to work on heaps, and someone else mentioned they wanted to work on balanced binary search trees.

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

ASSIGNMENT 5 Objects, Files, and a Music Player

CS 230 Programming Languages

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction

Carleton University Department of Systems and Computer Engineering SYSC Foundations of Imperative Programming - Winter 2012

} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2.

COMP-202 Unit 4: Programming with Iterations

Fall 2017 CISC124 9/16/2017

Introduction to Java & Fundamental Data Types

CS125 : Introduction to Computer Science. Lecture Notes #38 and #39 Quicksort. c 2005, 2003, 2002, 2000 Jason Zych

Carleton University Department of Systems and Computer Engineering SYSC Foundations of Imperative Programming - Winter 2012

CSCI 1100L: Topics in Computing Lab Lab 11: Programming with Scratch

5. PLEASE TAKE HOME the question bundle, but turn in 2 paper sheets: The scantron AND the paper where you wrote your programming question solution!

Programming In Java Prof. Debasis Samanta Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

CS 170 Java Programming 1. Week 15: Interfaces and Exceptions

Java Programming Constructs Java Programming 2 Lesson 1

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Inf1-OP. Inf1-OP Exam Review. Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein. March 20, School of Informatics

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

(Refer Slide Time: 00:26)

Working with recursion. From definition to template. Readings: HtDP, sections 11, 12, 13 (Intermezzo 2).

CS103 Spring 2018 Mathematical Vocabulary

CS110D: PROGRAMMING LANGUAGE I

Repetition Structures

CS201 - Assignment 3, Part 1 Due: Friday February 28, at the beginning of class

Eclipse Environment Setup

Carleton University Department of Systems and Computer Engineering SYSC Foundations of Imperative Programming - Winter 2012

CS 132 Exam #1 - Study Suggestions

CS Fall Homework 11 p. 1. CS Homework 11


Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Ar r ays and Pointer s

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

Two Types of Types. Primitive Types in Java. Using Primitive Variables. Class #07: Java Primitives. Integer types.

Lab 9: Pointers and arrays

Apple SIG Meeting January 4

PROFESSOR: Last time, we took a look at an explicit control evaluator for Lisp, and that bridged the gap between

Formal Methods of Software Design, Eric Hehner, segment 24 page 1 out of 5

Design and Analysis of Algorithms Prof. Madhavan Mukund Chennai Mathematical Institute. Week 02 Module 06 Lecture - 14 Merge Sort: Analysis

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #17. Loops: Break Statement

CS Week 14 Lab Exercise

Introduction to Computation and Problem Solving

CS 103 Lab The Files are *In* the Computer

Principle of Complier Design Prof. Y. N. Srikant Department of Computer Science and Automation Indian Institute of Science, Bangalore

Arduino IDE Friday, 26 October 2018

CS 170 Java Tools. Step 1: Got Java?

CS 170 Java Tools. Step 1: Got Java?

Lesson 3 Transcript: Part 1 of 2 - Tools & Scripting

Fundamentals of Programming Session 12

Lecture Transcript While and Do While Statements in C++

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

CS8 Final Exam E03, 09M, Phill Conrad, UC Santa Barbara 09/10/2009

Working with recursion

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

CSE 113 A. Announcements - Lab

(Refer Slide Time: 00:02:02)

Homework 11 Program Setup (with some IMPORTANT NEW STEPS!)

contain a geometry package, and so on). All Java classes should belong to a package, and you specify that package by typing:

Garbage Collection (1)

St. Edmund Preparatory High School Brooklyn, NY

Java Programming. Computer Science 112

ASSIGNMENT 5 Data Structures, Files, Exceptions, and To-Do Lists

19 Much that I bound, I could not free; Much that I freed returned to me. Lee Wilson Dodd

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #54. Organizing Code in multiple files

CS 170 Java Programming 1. Week 13: Classes, Testing, Debugging

MITOCW watch?v=zm5mw5nkzjg

Java Programming. Computer Science 112

CS108, Stanford Handout #8. Java Generics

Transcription:

CS 170 Java Programming 1 Using Loops to Initialize and Modify Array Elements Slide 1 CS 170 Java Programming 1 Duration: 00:01:27 Welcome to the CS170, Java Programming 1 lecture on. Loop Guru, the album by Duniya, features "Nearly 69 minutes of infectious electronic rhythms ranging from wirly dance grooves to worldly atmospheric shivers that take us from the dance floor to the chill room". Whatever; I just like the name of the album. Instead of wirly dance grooves, in this lecture we'll take a look at various ways that we can process arrays, many of them designed to turn you into a real loop guru. We'll look at: Algorithms that process and modify the elements of an entire array, such as initialization. Read-only algorithms that can make use of Java's foreach loop syntax for visiting each array element. Algorithms that process a portion of an array by using sentinel loops. Algorithms that modify a portion of an array by inserting or deleting elements. We'll pick up many of these topics next week. For right now, let's start by learning about the algorithms that process an entire array, and that may, (or may not) modify the array elements. This includes operations like initialization, sorting, and reversing the elements in an array, (something you'll need to do for the exercises). Real advantage of arrays? Apply repetitive processing to a group of variables. Need to use a loop Algorithms that may modify the elements of the array Initializing an array Sorting or otherwise rearranging elements Algorithms where position of items is significant Algorithms that need only to read the values Includes many counting and calculating problems We ll use different kinds of loops for each problem Slide 2 Duration: 00:00:53 The real advantage of arrays, is that they allow you to apply the same processing to all of the elements by using a loop. We can divide the processing of entire arrays into two kinds: 1. Algorithms that may modify the elements of the array as they are processed. This includes initialization, sorting, and otherwise rearranging items. It also includes algorithms where the position of the elements in the array is significant or must be noted. 2. Algorithms that need only to read the values contained in the array. These algorithms solve many counting and calculating problems. We'll use different kinds of loops for both types of algorithms, although you can use the modifying for loop on the read-only calculation problems as well. CS 170 Lecture: Page 1 of 5 2008-2075 Stephen Gilbert

Modifying Array Loops The for loop is the loop of choice The length field provides a natural count bound The modifying-loop-processing idiom or pattern Standard way to process an array when you want to visit every element and you need to modify the contents of an element or some of the elements 1. Retrieve the length of the array for the loop bounds 2. Write a loop that goes from 0 to length 1 3. Use subscript to modify elements in the loop body Slide 3 Modifying Array Loops Duration: 00:01:27 For array processing, where the elements may be modified, or where the positions of the elements is important, the for loop is the loop of choice, because the array.length field creates a natural counter that you can use to control the loop bounds, and because the loop index can be used as the subscript to access the array elements. To do this, you'll follow the modifying-loop-processing idiom or pattern. A pattern is like a recipe you use whenever you encounter a particular type of problem. The modifying-loopprocessing pattern is the standard way to process an array, when you want to visit every element, and, when you need to modify one or more of the elements. If you need to initialize an array to a value other than zero, for instance, the initializer list is useful only for short arrays. Typing in even 25 or 50 values can get very tedious. Instead, you should use a for loop that follows this pattern: 1. Retrieve the length of the array and use it as the loop's upper bounds. 2. Write a for loop that goes from 0 to less-than the upper bounds. 3. Assign a new value to each element that you wish to modify inside the loop body. Use the loop counter as the element's subscript. Let me show you an example, and then you can try a few on your own. Initialize an Array Example: Use a loop to initialize an array Fills an array with random values between 0 and len Assumes randnums is an array of doubles int len = randnums.length; for (int i = 0; i < len; i++) { randnums[i] = Math.random() * len; } Slide 4 Initialize an Array Duration: 00:01:17 Here's an example that uses this pattern to initialize an array. In this case, I'm going to fill each element in an array of doubles (randnum) with random values that fall somewhere between 0 and less than the length of the array. (If the length of the array was 10, the values could be anything from 0.0 to 9.99999). Notice the way that the code follows the recipe or pattern: 1. Retrieve the length of the array and use it as the loop's upper bounds. 2. Write a for loop that goes from 0 to less-than the upper bounds. Notice that when processing an array (or a String), you'll always want to use asymmetric bounds that is, bounds that start at 0 and go to less than the upper bound since both Strings and arrays are 0 based and the last element is always at len 1. You can read more about symmetric and asymmetric bounds in Quality Tip 6.3 on page 252 in your text. 3. Finally, we assign a new value to each element that we wish to modify inside the loop body, using the loop CS 170 Lecture: Page 2 of 5 2008-2075 Stephen Gilbert

counter as the element's subscript. Exercise 1: use loops to initialize each of these arrays previously defined in the run() method: ia to random numbers between 1 and 500. da to every 1.0 / every tenth element of ia ca to upper-case characters starting at 'A'. The even elements of fa with the index number / index number + 1 and the odd elements with 1 / index number. Remember to cast so you end up with the correct calculation and type in each element. Slide 5 Duration: 00:01:50 OK. Now it's your turn. Open Eclipse and the ArrayTest class. Inside the run() method, initialize each of these arrays that you previously defined in the run() method: Initialize ia to hold random numbers between 1 and 500. Initialize da so that each element contains 1.0/ every tenth element in the array ia. In other words, the first element will be 1.0/ the first element in ia. The second element in da will be 1.0/ the 10 th element in ia. The third element in da will be 1.0/ the 20 th element in ia and so on. Initialize ca to the upper-case characters starting at capital 'A'. For fa, initialize the even numbered elements (0, 2, 4, etc) with the subscript or index number divided by the index number + 1. Initialize the odd elements with 1 / index number. Remember to cast so that you Once you've finished, save your work (and make sure everything compiles with no red squiggleys). Then, run the program just to make sure you don't have any runtime errors. When the console window shows no errors, snap a picture. Create a new section in your IC document this week, and paste your picture in as Exercise 1. Exercise 2: write a method countevens() that takes one int array parameter. Use a loop to count and return the number of even ints in the array. Note that the % operator computes the remainder, so that a number is even if n % 2 == 0. When you are finished, run the JUnit test program, TestCountEvens and shoot a screenshot of all tests running green. Slide 6 Duration: 00:00:57 Let's try another exercise that processes all of the elements in the loop. The only difference between this and the previous one is that in the loop body, you won't modify the array elements, but simply examine them. Inside the ArrayTest program, write a method named countevens(). The countevens() method will take one parameter: an array of int. Use a loop to count the number of even ints in the array. (Note that this means you want to count the number of array values that are even, not the number of array subscripts that are even.) A number is even if n % 2 == 0. When you have finished with the method, and ArrayTest compiles, then runt the JUnit test program, TestCountEvens. Shoot me a screenshot for Exercise 2 showing both your code and the JUnit tests running all green. CS 170 Lecture: Page 3 of 5 2008-2075 Stephen Gilbert

In Java, methods can return arrays, just like objects The return type of the method is type[ ] Create a local array, process and then return it like this: public int[ ] makerandom(int howmany) { int[ ] ar = new int[ howmany ]; for(int i = 0; i < ar.length; i++) ar[ i ] = (int) (Math.random() * howmany); return ar; } Slide 7 Returning an Array Duration: 00:01:24 Returning an Array In the last lecture you learned how to pass an array variable to a method where it could be processed. Java also allows you to easily write methods that return array variables. As with passing array variables to a method, the only "trick" is in knowing how to declare the return type. Suppose, for instance, you wanted to write a method that returned an array of random integers. Your method header would look like this: public int[] makerandom(int howmany) {} Notice that the return type is declared as int[] and not int. Once you've figured out how to write the return type, the next question that arises is "How do you get the array variable to return?" The answer is simple--you create a local array variable inside your method, and then return the local variable. Here's the rest of the makerandom() method that shows you how. Notice that it: 1. Creates and initializes a local array variable using the int parameter howmany to determine the number of elements in the local array. 2. Uses the modifying-loop-processing pattern to visit every element in the local array 3. Fills each element with a random number 4. Returns the newly processed array Exercise 3: write a method evenints() that takes one int array parameter. Return a new array containing only the even ints in the parameter. That is, if the parameter contains {1, 2, 3, 4} you would return an array containing {2, 4}. If there are no even ints, just return a new array of length 0. Make sure that the parameter is not modified. When you are finished, run the JUnit test program, TestEvenInts and shoot a screenshot of all tests running green. Let's finish up this week with an exercise that returns an array. Inside ArrayTest, add a new method, evenints that takes one int array parameter. The method should also return an int array. Inside the method, create a new array containing only the ints with even values. For instance, if you supply an array containing the values 1, 2, 3, and 4, then the returned array would only contain 2 and 4 that is, the even integers. If there are no even integers in the input array, then return a new array of length 0. Make sure when you write this program, that you don't modify the elements in the input array. To find the size of the CS 170 Lecture: Page 4 of 5 2008-2075 Stephen Gilbert

Slide 8 Duration: 00:01:12 output array, you can call the countevens() method that you wrote for Exercise 2, or you can simply use a second loop. When you are finished, run the JUnit test program, TestEvenInts and shoot me a screenshot showing both your code and all of the tests running green. Well, that's it for this week. See you next week. CS 170 Lecture: Page 5 of 5 2008-2075 Stephen Gilbert