CS-259 Computer Programming Fundamentals Arrays

Similar documents
Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

CSC 160 LAB 8-1 DIGITAL PICTURE FRAME. 1. Introduction

15. Arrays and Methods. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Spring University of New Mexico CS152 Midterm Exam. Print Your Name

CMP 326 Midterm Fall 2015

1.00/1.001 Introduction to Computers and Engineering Problem Solving Fall (total 7 pages)

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable?

CS 152 Computer Programming Fundamentals The if-else Statement

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

Practice Midterm 1. Problem Points Score TOTAL 50

Midterm I - CSE11 Fall 2013 CLOSED BOOK, CLOSED NOTES 50 minutes, 100 points Total.

First Exam Computer Programming 326 Dr. St. John Lehman College City University of New York Thursday, 7 October 2010

Nested Loops. A loop can be nested inside another loop.

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

SampleApp.java. Page 1

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008

Practice Midterm 1 Answer Key

1.00 Introduction to Computers and Engineering Problem Solving. Quiz 1 March 7, 2003

CSC 1051 Algorithms and Data Structures I. Final Examination May 12, Name

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

(A) 99 (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

1.00 Introduction to Computers and Engineering Problem Solving Quiz 1 March 4, 2005

Computer Programming, I. Laboratory Manual. Final Exam Solution

The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT

Chapter 5 Names, Bindings, Type Checking, and Scopes

Answer on question #61311, Programming & Computer Science / Java

Example: Building a Java GUI

AP CS Unit 11: Graphics and Events

Computer Science II (20082) Week 1: Review and Inheritance

Example: Building a Java GUI

COMPUTER APPLICATIONS

University of Cape Town ~ Department of Computer Science. Computer Science 1016S / 1011H ~ January Exam

CS 110 Practice Final Exam originally from Winter, Instructions: closed books, closed notes, open minds, 3 hour time limit.

Use the Scantron sheets to write your answer. Make sure to write your Purdue ID (NOT Purdue Login ID) and your name on the Scantron answer sheet.

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Name Section Number. CS110 Exam #1 *** PLEASE TURN OFF ALL CELLPHONES ***

More About Classes CS 1025 Computer Science Fundamentals I Stephen M. Watt University of Western Ontario

CS 231 Data Structures and Algorithms Fall Event Based Programming Lecture 06 - September 17, Prof. Zadia Codabux

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

1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4'

CS111: PROGRAMMING LANGUAGE II

if (x == 0); System.out.println( x=0 ); if (x = 0) System.out.println( x=0 );

(A) 99 ** (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

Mr. Monroe s Guide to Mastering Java Syntax

COMP16121 Notes on Mock Exam Questions

RAIK 183H Examination 2 Solution. November 10, 2014

Page 1 of 16. Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

ANSWER KEY First Exam Computer Programming 326 Dr. St. John Lehman College City University of New York Thursday, 7 October 2010

CS 101 Fall 2006 Midterm 3 Name: ID:

CS 134 Programming Exercise 7:

CS 351 Design of Large Programs

Java-Array. This tutorial introduces how to declare array variables, create arrays, and process arrays using indexed variables.

CS-257L Nonimperative Programming: Scheme!

Queens College, CUNY Department of Computer Science. CS 212 Object-Oriented Programming in Java Practice Exam 2. CS 212 Exam 2 Study Guide

G51PGP Programming Paradigms. Lecture 008 Inner classes, anonymous classes, Swing worker thread

MIT AITI Swing Event Model Lecture 17

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 10 INTRODUCTION TO ARRAYS

AP Computer Science A Unit 2. Exercises

CPS109 Lab 7. Source: Big Java, Chapter 7 Preparation: read Chapter 7 and the lecture notes for this week.

Fundamentals of Object Oriented Programming

Array. Array Declaration:

CSC 1051 Algorithms and Data Structures I. Final Examination May 12, Name: KEY. Question Value Score

Systems Programming. Bachelor in Telecommunication Technology Engineering Bachelor in Communication System Engineering Carlos III University of Madrid

CS 302 Week 9. Jim Williams

The JFrame Class Frame Windows GRAPHICAL USER INTERFACES. Five steps to displaying a frame: 1) Construct an object of the JFrame class

Unit 10: Data Structures CS 101, Fall 2018

CSE 142, Autumn 2008 Midterm Exam, Friday, October 31, 2008

This exam is open book. Each question is worth 3 points.

RAIK 183H Examination 2 Solution. November 11, 2013

CS 61B Discussion Quiz 1. Questions

Welcome to the Using Objects lab!

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

Final Exam. COMP Summer I June 26, points

Building Java Programs

AplusBug dude = new AplusBug(); A+ Computer Science -

cs Java: lecture #6

2 What are the differences between constructors and methods?

Building Java Programs

Chapter 8 Objects and Classes Dr. Essam Halim Date: Page 1

Introduction to Functional Programming in Java 8

AP CS Unit 12: Drawing and Mouse Events

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

class objects instances Fields Constructors Methods static

CPSC 219 Extra review and solutions

Practice Questions for Chapter 9

University of Palestine. Mid Exam Total Grade: 100

CS 211: Methods, Memory, Equality

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

University of Cape Town ~ Department of Computer Science Computer Science 1015F ~ Test 2. Question Max Mark Internal External

1 Short Answer (10 Points Each)

CS 177 Week 15 Recitation Slides. Review

Recap: Assignment as an Operator CS 112 Introduction to Programming

Course overview: Introduction to programming concepts

CS Week 5. Jim Williams, PhD

Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters

CSE 131 Introduction to Computer Science Fall Exam II

CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall Office hours:

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

1 If you want to store a letter grade (like a course grade) which variable type would you use? a. int b. String c. char d. boolean

Transcription:

CS-9 Computer Programming Fundamentals Arrays int a = new int[]; Instructor: Joel Castellanos e-mail: joel@unm.edu And in such indexes, although small pricks To their subsequent volumes, there is seen The baby figure of the giant mas Of things to come at large. --William Shakespeare, Troilus and Cressida //6 Textbook & Reading Assignment Introduction to java Programming ( th Edition) by Y. Daniel Liang Read by Wednesday: Sept 8 Chapter 7: Arrays Sections through. Study Questions: 7., 7.6, 7.7, 7.8, 7. Read by Friday: Sept Chapter 7: Arrays Sections 6 through end of chapter.

An Index (plural: indexes) In publishing, an index is a list of words or phrases, "headings", and associated pointers "locators" to where useful material relating to that heading can be found in a document. In a traditional back-of-the-book index, the headings will include names of people, places and events, and concepts selected by a person as being relevant and of interest to a possible reader of the book. The pointers are typically page numbers, paragraph numbers or section numbers. In a library catalog the words are authors, titles, subject headings, etc., and the pointers are call numbers. The Array 4 In Java, an array is collection of data items allocated in sequential memory locations that can be selected by indices computed at run-time. ) int[] a; ) int[] b = {,,,, }; ) int[] c = new int[]; 4) c[767] = 9; ) a = b; 6) System.out.println(a[i]); No matter how large an array, a particular element can be loaded or stored in constant time. a b c

Arrays: Fibonacci Series ) //Example without an array ) int f = ; ) int f = ; 4) int f = f + f; ) int f = f + f; 6) int f4 = f + f; 7) int f = f4 + f; 8) int f6 = f + f4; 9) ) System.out.println(f + " " + f + " " ) + f + " " + f + " " + f4 + " " + f ) + " " + f6); ) 4) // 8 Arrays: Fibonacci Series 6 ) //Example with an array ) int[] f = new int[7]; ) f[] = ; 4) f[] = ; ) f[] = f[] + f[]; 6) f[] = f[] + f[]; 7) f[4] = f[] + f[]; 8) f[] = f[4] + f[]; 9) f[6] = f[] + f[4]; ). int[] f declares f as a reference to an int array.. f = new int[7] reserves memory for 7 int variables and sets f to reference that block of memory. ) System.out.println(f[] + " " + f[] ) + " " + f[] + " " + f[] + " " + f[4] ) + " " + f[] + " " + f[6]); 4) // 8

Array Versatility: Fibonacci Series 7 ) //Example array In Java, arrays ) int[] f = new int[4]; hava a field ) f[] = ;.length not a method 4) f[] = ;.length(). ) for (int i=; i<f.length; i++) 6) { f[i] = f[i-] + f[i-]; By contrast, a 7) } String has a 8) method.length() not 9) for (int i=; i<f.length; i++) a field.length. ) { System.out.print(f[i] + " "); ) } ) System.out.println(); ) 4) // 8 4 89 44 77 Quiz: Arrays and Fibonacci Series In the Java code below, which lines can be swapped (have their positions interchanged) without causing an error or changing the output? ) int[] f = new int[6]; ) f[] = ; ) f[] = ; 4) for (int i=; i<f.length; i++) ) { 6) System.out.println(f[i-]); 7) f[i] = f[i-] + f[i-]; 8) } 8 a) & b) & 4 c) 4 & d) 4 & 6 e) 6 & 7 4

Helper Method: printarray ) public static void printarray(int[] array) ) { ) System.out.print("{ "); 4) for (int i=; i<array.length; i++) ) { 6) System.out.print(array[i] +" "); 7) } 8) System.out.println("}"); 9) } Why make this public? 9 Quiz: find max ) int[] numlist = {,,,,, }; ) ) int max = numlist[]; 4) for (int i=; i<numlist.length; i++) ) { if (numlist[i] > max) 6) { System.out.print(max+" "); 7) max=numlist[i]; 8) } 9) } ) System.out.println(); max= max = max= What is the output of the above code segment? a) b) c) d) e)

Find The Syntax Error ) int[] numlist = {,,,,, }; ) ) int max = numlist; 4) Type mismatch: Cannot Convert form int[] to int ) 6) for (int i=; i<numlist.length; i++) 7) { 8) if (numlist[i] > max) 9) { ) System.out.print(max+" "); ) max=numlist[i]; ) } )} 4)System.out.println(); Quiz: find max ) int[] numlist = {, 7,, 7, 8}; ) ) int max = numlist[]; 4) for (int i=; i<numlist.length; i++) ) { System.out.print(i + "(" +max+") "); 6) if (numlist[i] > max) 7) { max=numlist[i]; 8) } 9) } ) System.out.println(); What is the output of the above code segment? a) () (7) () (7) 4(8) b) () (7) () 4(7) (8) c) () (7) () 4(8) d) () () () 4(7) e) () () () 4() 6

Array Reference Copy ) public static void main(string[] args) ) { int[] a = {,,,, }; ) int[] b = a; 4) b[] = ; ) System.out.println( 6) a[] + ", " + a[] + ", " + b[]); 7) } Line Line Line 4 a a b a b Array Element Copy 4 ) public static void main(string[] args) ) { int[] a = {,,,, }; ) int[] b = new int[]; 4) for (i=; i<a.length; i++) ) { b[i]=a[i]; 6) } 7) b[] = 8; 8) System.out.println( 9) a[] + ", " + a[] + ", " + b[]); ) } a b a b 8 7

Quiz: Array Copying. public static void main(string[] args). { int[] a = {,,,,, 8};. int[] b = a; 4. b[] = 7;. System.out.println( 6. a[] + ", " + a[] + ", " + b[]); 7. } The output is: a) 7, 7, 7 b), 7, 7 c),, 7 d),, 7 e),, Allocating Space for Arrays of Objects 6 ) //Allocates space for three -bit integers. ) int[] x = new int[]; ) 4) //Allocates space for three references. ) JFrame[] frames = new JFrame[]; 6) 7) for (int i = ; i<; i++) 8) { 9) x[i] = i; ) JFrame constructor NOT called. JFrame constructor IS called. ) //Create each of the JFrame instances. ) p[i] = new JFrame(); ) frames[i].setbounds(i*,i*,, ); 4) frames[i].setvisible(true); ) } Without line, line will cause a Null Pointer Exception. 8

7 Comparing Array References. public static void main(string[] args). { int[] a = {,,,, 7};. int[] b = {,,,, 7}; 4. if (a==b). { System.out.println("yes"); 6. } 7. else System.out.println("no"); 8. } Output: no a 7 b 7 Quiz: On Which line is the Syntax Error? public class SyntaxQuiz { public static double abs(double a) { if (a <.) return -a; return a; } 8 public static void main(string[] args) { double[] x = {., -.4, 7.}; int i = ; a) System.out.println(abs(x[])); b) System.out.println(abs(x[i])); c) System.out.println(abs(x)); d) System.out.println(abs(i)); e) System.out.println(abs(x[] - x[])); } } 9

BouncingLines 9 ) Start with BouncingLine.java. ) BouncingLine.java uses int x, y, x, y to maintain the location of the line's two endpoints. ) Transform BouncingLine.java to use arrays int[] x, y, x, y to maintain a history of the line's endpoints. 4) After drawing NUM_LINES, each time step, erase the oldest line in the history and replace it with the line's new location. BouncingLines: imports ) import java.awt.color; ) import java.awt.graphics; ) import java.awt.event.actionevent; 4) import java.awt.event.actionlistener; ) import java.util.random; 6) import javax.swing.timer;

BouncingLines: Class and Instance Fields ) public class BouncingLines implements ActionListener ) { ) private Random rand = new Random(); 4) private Timer mytimer; ) private Picture mypic; 6) private Graphics canvas; 7) 8) private static final int DRAW_WIDTH = 6; 9) private static final int DRAW_HEIGHT = 6; ) private static final int NUM_LINES = ; ) ) private int[] x = new int[num_lines]; ) private int[] x = new int[num_lines]; Parallel 4) private int[] y = new int[num_lines]; Arrays ) private int[] y = new int[num_lines]; 6) private int curidx = ; 7) 8) private int speedx, speedx, speedy, speedy; Data Structure: Circular, Parallel Arrays private int[] x = new int[num_lines]; private int[] x = new int[num_lines]; private int[] y = new int[num_lines]; private int[] y = new int[num_lines]; 4 6 7 8 9 x y x y Newest line Oldest Line curidx nextidx

BouncingLines: main public static void main(string[] args) { new BouncingLines(); } 4 BouncingLines: Constructor ) public BouncingLines() ) { ) mypic = new Picture(DRAW_WIDTH, DRAW_HEIGHT); ) canvas = mypic.getoffscreengraphics(); 4) canvas.setcolor(color.white); ) canvas.fillrect(,, DRAW_WIDTH, DRAW_HEIGHT); 6) mypic.settitle("bounding Lines"); 7) 8) x[] = rand.nextint(draw_width); 9) y[] = rand.nextint(draw_height); ) x[] = rand.nextint(draw_width); ) y[] = rand.nextint(draw_height); ) ) speedx = rand.nextint()-; 4) speedy = rand.nextint()-; ) speedx = rand.nextint()-; 6) speedy = rand.nextint()-; 7) 8) mytimer = new Timer(, this); // miliseconds 9) mytimer.start(); 4) }

BouncingLines: actionperformed ( of ) ) public void actionperformed(actionevent arg) ) { ) //Let nextidx be the index of the oldest line. ) int nextidx = (curidx+) % NUM_LINES; ) //Erase oldest line. 6) //Move newest line and store its endpoints at index where // the oldest line was stored. 7) //If next line is out of bounds in the horizontal direction, then // give it a random horizontal speed in the opposite direction. //If next line is out of bounds in the vertical direction, then // give it a random vertical speed in the opposite direction. 9) //Update the current line index. 9) //Draw the new line 99) } BouncingLines: actionperformed ( of ) ) public void actionperformed(actionevent arg) ) { ) //Let nextidx be the index of the oldest line. ) int nextidx = (curidx+) % NUM_LINES; 4) ) //Erase oldest line. 6) canvas.setcolor(color.white); 7) canvas.drawline(x[nextidx], y[nextidx], 8) x[nextidx], y[nextidx]); 6

BouncingLines: actionperformed ( of ) 6) //Move newest line and store its endpoints at index 6) // where the oldest line was stored. 6) x[nextidx] = x[curidx] + speedx; 6) y[nextidx] = y[curidx] + speedy; 64) 6) x[nextidx] = x[curidx] + speedx; 66) y[nextidx] = y[curidx] + speedy; 67) 68) 7 BouncingLines: actionperformed (4 of ) 7) //If next line is out of bounds in the horizontal direction, then 7) // give it a random horizontal speed in the opposite direction. 7) //If next line is out of bounds in the vertical direction, then 7) // give it a random vertical speed in the opposite direction. 74) if (x[nextidx] < ) speedx = rand.nextint()+; 7) if (y[nextidx] < ) speedy = rand.nextint()+; 76) 77) if (x[nextidx]>draw_width) speedx =-(rand.nextint()+); 78) if (y[nextidx]>draw_height) speedy=-(rand.nextint()+); 79) 8) 8) 8) if (x[nextidx] < ) speedx = rand.nextint()+; 8) if (y[nextidx] < ) speedy = rand.nextint()+; 84) 8) if (x[nextidx]>draw_width) speedx =-(rand.nextint()+); 86) if (y[nextidx]>draw_height) speedy=-(rand.nextint()+); 87) 8 4

BouncingLines: actionperformed ( of ) 9) //Update the current line index. 9) curidx = nextidx; 9) 9) //Draw the new line 94) canvas.setcolor(color.red); 9) canvas.drawline(x[curidx], y[curidx], 96) x[curidx], y[curidx]); 97) mypic.repaint(); 98) 99)} 9