More on variables, arrays, debugging

Similar documents
TESTING AND DEBUGGING

I/O (cont) and Program Development. Standard Audio. A Foundation for Programming. Crash Course in Sound

Program Development. Program Development. A Foundation for Programming. Program Development

1.3 Conditionals and Loops

Arrays to the rescue!

Lecture 3: Loops. While Loops. While Loops: Powers of Two. While Loops: Newton-Raphson Method

Mul$dimensional arrays. CSCI 136: Fundamentals of Computer Science II Keith Vertanen

A Foundation for Programming

1.3 Conditionals and Loops

Lecture 3: Loops. While Loops. While Loops: Newton-Raphson Method. While Loops: Powers of Two

2.3 Flow Control. Flow-Of-Control. If-Else: Leap Year. If-Else

3. Conditionals & Loops

3. Conditionals and loops

! Sequence of statements that are actually executed in a program. ! Conditionals and loops: enable us to choreograph control flow.

3. Conditionals & Loops

Debugging [continued]

1.3 Conditionals and Loops. 1.3 Conditionals and Loops. Conditionals and Loops

AP CS Unit 3: Control Structures Notes

1.3 Conditionals and Loops

You have seen abstractions in many places, lets consider them from the ground up.

Debugging [continued]

Array Basics: Outline

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

Conditionals, Loops, and Style

Array Basics: Outline

COMP-202 Unit 4: Programming with Iterations

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Conditionals, Loops, and Style. Control flow thus far. if statement. Control flow. Common branching statement Evaluate a boolean expression

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

Nested Loops ***** ***** ***** ***** ***** We know we can print out one line of this square as follows: System.out.

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

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

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

Controls Structure for Repetition

Lecture 14 CSE11 Fall 2013 For loops, Do While, Break, Continue

Repetition with for loops

CS1150 Principles of Computer Science Loops (Part II)

Pull Lecture Materials and Open PollEv. Poll Everywhere: pollev.com/comp110. Lecture 12. else-if and while loops. Once in a while

Definite Loops. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

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

A Walkthrough of the Learning Aids

COMP-202: Foundations of Programming. Lecture 8: for Loops, Nested Loops and Arrays Jackie Cheung, Winter 2016

CS125 : Introduction to Computer Science. Lecture Notes #6 Compound Statements, Scope, and Advanced Conditionals

CS 177 Recitation. Week 1 Intro to Java

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false.

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

Array Basics: Outline

CSE 20. SAMPLE FINAL Version A Time: 180 minutes. The following precedence table is provided for your use:

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

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

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

Object Oriented Programming Exception Handling

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

Java Programming. Computer Science 112

Tutorials. Inf1-OP. Learning Outcomes for this week. A Foundation for Programming. Conditionals and Loops 1

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

Primitive Data, Variables, and Expressions; Simple Conditional Execution

STUDENT LESSON A12 Iterations

Fundamentals of Object Oriented Programming

A function is a named piece of code that performs a specific task. Sometimes functions are called methods, procedures, or subroutines (like in LC-3).

Boot Camp. Dave Eckhardt Bruce Maggs

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

BBM 102 Introduction to Programming II Spring Exceptions

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

Write for your audience

COMP 202 Java in one week

1 Getting used to Python

Get JAVA. I will just tell you what I did (on January 10, 2017). I went to:

Jerry Cain Handout #5 CS 106AJ September 30, Using JSKarel

Building Java Programs Chapter 2. bug. Primitive Data and Definite Loops. Copyright (c) Pearson All rights reserved. Software Flaw.

Building Java Programs Chapter 2

Lab # 2. For today s lab:

Primitive data, expressions, and variables

CP122 CS I. Iteration

GB Programming Challenges

Math Modeling in Java: An S-I Compartment Model

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

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

CS 302: Introduction to Programming in Java. Lecture 11 Yinggang Huang. CS302 Summer 2012

CONDITIONAL EXECUTION

SESSION 3 Programming Languages for Objects

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

PROGRAMMING STYLE. Fundamentals of Computer Science I

Computer Science is...

CIS March 1, 2018

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

The keyword list thus far: The Random class. Generating "Random" Numbers. Topic 16

Lecture 05: Methods. AITI Nigeria Summer 2012 University of Lagos.

Michele Van Dyne Museum 204B CSCI 136: Fundamentals of Computer Science II, Spring

Java Programming Fundamentals - Day Instructor: Jason Yoon Website:

10 Control and Iteration

Introduction to Computer Science Unit 2. Notes

Topic 16. battle -they are strictly limited in number, they require fresh horses, and must only be made at decisive moments." -Alfred North Whitehead

CIS 110: Introduction to Computer Programming

L o o p s. for(initializing expression; control expression; step expression) { one or more statements }

CS 102/107 - Introduction to Programming Midterm Exam #2 - Prof. Reed Spring 2011

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner

CONTENTS: Arrays Strings. COMP-202 Unit 5: Loops in Practice

Transcription:

More on variables, arrays, debugging zombie[1] zombie[3] Buuuuugs zombie[4] zombie[2] zombie[5] zombie[0] Fundamentals of Computer Science Keith Vertanen

Variables revisited Scoping Arrays revisited Overview Mul<dimensional arrays Debugging Tip and tricks to help you keep your sanity 2

Variable scoping Variables live within their curly braces Once curly block finishes, variable is gone! public class DoStuff public static void main(string [] args) int x = 0; for (int y = 0; y < 5; y++) x = x + y; x = x * y; y only lives in the for- loop y is undefined, this won't compile! 3

Variable scoping You can declare and reuse same name again But only ajer no longer "in scope" public class DoStuff public static void main(string [] args) int x = 0; for (int y = 0; y < 5; y++) x = x + y; int y = 1; x = x * y; This fixes the compile error (though doesn't really do anything useful). 4

Arrays Arrays revisited Store a bunch of values under one name Declare and create in one line: int N = 8; int [] x = new int[10]; double [] speeds = new double[100]; String [] names = new String[N]; To get at values, use name and index between []: int sumfirst2 = x[0] + x[1]; speeds[99] = speeds[98] * 1.1; System.out.println(names[0]); Array indexes start at 0! 5

Arrays Arrays revisited You can just declare an array: int [] x; But x is not very useful un<l you "new" it: int [] x; x = new int[7]; new creates the memory for the slots Each slot holds an independent int value Each slot ini<alized to default value for type 6

Arrays revisited x Variable x refers to the whole set of slots You can't use the variable x by itself for much Except for finding out the number of slots: x.length 7

Arrays revisited x[0] x[1] x[2] x[3] x[4] x[5] x[6] x x[0],x[1],,x[6] refers to value at a par<cular slot x[- 1] or x[7] = ArrayIndexOutOfBoundsException 8

Arrays revisited x[0] x[1] x[2] x[3] x[4] x[5] x[6] x[i] x x[i] refers to the value at a slot, but the slot index is determined by variable i If i = 0 then x[0], if i = 1 then x[1], etc. Whatever inside [] must be an int Whatever inside [] must be in 0 to x.length - 1 (inclusive) 9

Two dimensional array examples Two dimensional arrays Tables of hourly temps for last week Table of colors for each pixel of a 2D image Table storing piece at each posi<on on a checkerboard 0h 1h 23h 32.5 30.0 45.6 59.5 62.1 60.0 60.7 61.8 70.5 62.6 62.0 68.0 10

Weather data Goal: Read in hourly temp data for last week Each row is a day of the week Each column is a par<cular hour of the day 01:53 20:53 45.0 48.0 48.9 48.9 48.0 46.0 45.0 46.9 45.0 48.2 48.2 48.2 55.9 57.0 59.0 57.9 57.9 57.2 54.0 50.0 48.9 46.9 44.6 45.0 10/24/11 44.1 43.0 43.0 43.0 39.9 37.9 37.4 39.0 39.0 39.0 39.0 37.9 39.2 41.0 41.0 41.0 39.0 37.9 36.0 35.6 33.8 32.0 32.0 30.2 30.2 28.0 27.0 23.0 23.0 23.0 19.9 19.0 19.0 23.0 30.9 33.1 34.0 37.0 35.6 36.0 32.0 32.0 32.0 27.0 27.0 25.0 21.9 23.0 21.9 21.0 21.0 21.0 19.4 17.6 17.6 17.6 19.4 19.0 21.0 26.1 34.0 37.4 39.0 41.0 41.0 39.0 37.0 37.0 37.0 34.0 35.1 34.0 33.8 32.0 37.0 30.9 32.0 34.0 33.1 30.9 32.0 35.1 39.0 41.0 39.9 42.1 43.0 43.0 42.1 39.9 36.0 33.1 27.0 25.0 23.0 19.9 19.9 19.0 18.0 16.0 16.0 15.1 14.0 14.0 15.1 21.0 27.0 34.0 41.0 48.0 52.0 50.0 51.1 50.0 46.0 48.9 44.1 44.1 39.9 39.2 10/29/11 46.0 46.0 45.0 44.6 44.1 44.1 44.1 44.1 42.1 42.1 42.8 44.1 45.0 46.9 46.0 44.1 44.1 42.8 39.0 37.0 35.1 35.1 30.9 30.0 11

Two dimensional arrays Declaring and crea<ng Like 1D, but another pair of brackets: final int DAYS = 7; final int HOURS = 24; double [][] a = new double[days][hours]; Accessing elements To specify element at the i th row and j th column: a[i][j] a[0][0] a[0][1] a[0][2]... a[0][22] a[0][23] a[1][0] a[1][1] a[1][2] a[1][22] a[1][23]. a[6][0] a[6][1] a[6][2] a[6][22] a[6][23] Temperature on second day of data, last hour of day 12

Reading temperature data Ini<alize all elements of our 2D array Nested loop reading in each value from StdIn Find weekly max and min temp final int DAYS = 7; final int HOURS = 24; double [][] a = new double[days][hours]; double min = Double.POSTIVE_INFINITY; double max = Double.NEGATIVE_INFINITY; Start the min at a really high temp. Start the max at a really low temp. for (int row = 0; row < DAYS; row++) for (int col = 0; col < HOURS; col++) The new min temp is either the current a[row][col] = StdIn.readDouble(); min = Math.min(min, a[row][col]); min or the new max = Math.max(max, a[row][col]); data point. System.out.println("min = " + min + ", max = " + max); 13

Debugging Majority of program development <me: Finding and fixing mistakes! a.k.a. bugs It's not just you: bugs happen to all programmers 14

Debugging Computers can help find bugs But: computer can't automa<cally find all bugs! Computers do exactly what you ask Not necessarily what you want There is always a logical explana<on! Make sure you saved & compiled last change As soon as we started programming, we found out to our surprise that it wasn't as easy to get programs right as we had thought. Debugging had to be discovered. I can remember the exact instant when I realized that a large part of my life from then on was going to be spent in finding mistakes in my own programs. - Maurice Wilkes There has never been an unexpectedly short debugging period in the history of computers. - Steven Levy 15

Have a plan Preven<ng bugs Write out steps in English before you code Write comments first before tricky bits Use good coding style Good variable names "Name variables as if your first born child" If variable is called area it should hold an area! Split complicated stuff into manageable steps () s are free, force order of opera<ons you want Carefully consider loop bounds Listen to Eclipse (IDE) feedback 16

Finding bugs How to find bugs Add debug print statements Print out state of variables, loop values, etc. Remove before submimng Use debugger in your IDE Won't work if using file redirec<on Talk through program line- by- line Explain it to a: Programming novice Rubber duckie Teddy bear Poned plant 17

Problem: Debugging example For integer N > 1, compute its prime factoriza@on 98 = 2 x 7 2 17 = 17 154 = 2 x 7 x 11 16,562 = 2 x 7 2 x 13 2 3,757,208 = 2 3 x 7 13 2 x 397 11,111,111,111,111,111 = 2,071,723 x 5,363,222,357 Possible applica<on: Break RSA encryp<on Factor 200- digit numbers Used to secure Internet commerce 18

Problem: A simple algorithm For integer N > 1, compute its prime factoriza@on Algorithm: Star<ng with i=2 Repeatedly divide N by i as long as it evenly divides, output i every <me it divides Increment i Repeat 19

Example run i N Output 2 16562 2 3 8281 4 8281 5 8281 6 8281 7 8281 7 7 8 169 9 169 10 169 11 169 12 169 13 169 13 13 14 1 1 20

Buggy factoriza<on program public class Factors public static void main(string [] args) long n = Long.parseLong(args[0]) for (i = 0; i < n; i++) while (n % i == 0) System.out.print(i + " ") n = n / i This program has many bugs! 21

Debugging: syntax errors public class Factors public static void main(string [] args) long n = Long.parseLong(args[0]); for (int i = 0; i < n; i++) while (n % i == 0) System.out.print(i + " "); n = n / i; Syntax errors Illegal Java program Usually easily found and fixed 22

Debugging: seman<c errors public class Factors public static void main(string [] args) long n = Long.parseLong(args[0]); for (int i = 0; i < n; i++) while (n % i == 0) System.out.print(i + " "); n = n / i; Seman<c error Legal but wrong Java program Run program to iden<fy problem Need to start at 2 since 0 and 1 cannot be factors. % java Factors 98 Exception in thread "main" java.lang.arithmeticexception: / by zero at Factors.main(Factors.java:8) 23

Debugging: seman<c errors public class Factors public static void main(string [] args) long n = Long.parseLong(args[0]); for (int i = 2; i < n; i++) while (n % i == 0) System.out.print(i + " "); n = n / i; % java Factors 98 Indenta<on does does imply a block of code. 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2... 24

Debugging: even more problems public class Factors public static void main(string [] args) long n = Long.parseLong(args[0]); for (int i = 2; i < n; i++) while (n % i == 0) System.out.print(i + " "); n = n / i; % java Factors 98 2 7 7 % % java Factors 5 Need newline No output??? % java Factors 6 2 % Missing the 3??? 25

Debugging: adding trace print statement public class Factors public static void main(string [] args) long n = Long.parseLong(args[0]); for (int i = 2; i < n; i++) while (n % i == 0) System.out.println(i + " "); n = n / i; System.out.println("TRACE " + i + " " + n); % java Factors 5 TRACE 2 5 TRACE 3 5 TRACE 4 5 % java Factors 6 2 TRACE 2 3 i for- loop should go up to n! 26

Success? public class Factors public static void main(string [] args) long n = Long.parseLong(args[0]); for (int i = 2; i <= n; i++) while (n % i == 0) System.out.print(i + " "); n = n / i; System.out.println(); Fixes the lack of line feed problem. % java Factors 5 5 % java Factors 6 2 3 % java Factors 98 2 7 7 Fixes the "off- by- one" error in the loop bounds. % java Factors 3757208 2 2 2 7 13 13 397 27

Except for really big numbers... public class Factors public static void main(string [] args) long n = Long.parseLong(args[0]); for (int i = 2; i <= n; i++) while (n % i == 0) System.out.print(i + " "); n = n / i; System.out.println(); % java Factors 11111111 11 73 101 137 % java Factors 11111111111 21649 51329 % java Factors 11111111111111 11 239 4649 909091 % java Factors 11111111111111111 2071723-1 - 1-1 - 1-1 - 1-1... 28

Correct, but too slow public class Factors public static void main(string [] args) long n = Long.parseLong(args[0]); for (long i = 2; i <= n; i++) while (n % i == 0) System.out.print(i + " "); n = n / i; System.out.println(); % java Factors 11111111 11 73 101 137 % java Factors 11111111111 21649 51329 % java Factors 11111111111111 11 239 4649 909091 % java Factors 11111111111111111 2071723 5363222357 29

Faster version public class Factors public static void main(string [] args) long n = Long.parseLong(args[0]); for (long i = 2; i*i <= n; i++) while (n % i == 0) System.out.print(i + " "); n = n / i; System.out.println(); % java Factors 98 2 7 7 % java Factors 11111111 11 73 101 Missing last factor % java Factors 11111111111 21649 % java Factors 11111111111111 11 239 4649 % java Factors 11111111111111111 2071723 30

Fixed faster version public class Factors public static void main(string [] args) long n = Long.parseLong(args[0]); for (long i = 2; i*i <= n; i++) while (n % i == 0) System.out.print(i + " "); n = n / i; if (n > 1) System.out.println(n); else System.out.println(); Handles the "corner case" % java Factors 98 2 7 7 % java Factors 11111111 11 73 101 137 Need special case to print biggest factor (unless it occurs more than once) % java Factors 11111111111 21649 513239 % java Factors 11111111111111 11 239 4649 909091 % java Factors 11111111111111111 2071723 5363222357 31

Factors: analysis How large an integer can I factor? % java Factors 3757208 2 2 2 7 13 13 397 % java Factors 9201111169755555703 9201111169755555703 digits (i <= n) (i*i <= n) 3 instant instant 6 0.15 seconds instant 9 77 seconds instant 12 21 hours * 0.16 seconds 15 2.4 years * 2.7 seconds 18 2.4 millennia * 92 seconds * es<mated 32

Incremental development Split development into stages: Test thoroughly ajer each stage Don't move on un<l it's working! Bugs are (more) isolated to the part you've just been working on Prevents confusion caused by simultaneous bugs in several parts 33

Variables Summary Live within their curly braces Arrays Hold a set of independent values of same type Access single value via index between [] s Debugging Have a plan before coding, use good style Learn to trace execu<on On paper, with print statements, using the debugger Explain it to a teddy bear Incremental development 34