A Foundation for Programming

Similar documents
Program Development. Program Development. A Foundation for Programming. Program Development

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

1.3 Conditionals and Loops

1.3 Conditionals and Loops

TESTING AND DEBUGGING

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

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

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

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

3. Conditionals & Loops

3. Conditionals and loops

3. Conditionals & Loops

More on variables, arrays, debugging

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

Debugging [continued]

Debugging [continued]

1.1 Your First Program

A human being should be able to change a diaper, plan an invasion, butcher a hog, conn a ship, design a building, write a sonnet, balance accounts,

1.1 Your First Program

CS 177 Recitation. Week 1 Intro to Java

1.1 Your First Program

Java Bytecode (binary file)

1.1 Your First Program

1 Getting used to Python

List of Slides 1 Title 2 Chapter 2: Sequential execution and program errors 3 Chapter aims 4 Section 2: Example:Hello world 5 Aim 6 Class: programs ar

Lecture 2: Intro to Java

1.1 Your First Program

1.1 Your First Program

17 Hello world 18 Type: String: literal 19 Standard API: System: out.println() 20 Hello world 21 Statement 22 Statement: simple statements are ended w

1.1 Your First Program

! Widely available. ! Widely used. ! Variety of automatic checks for mistakes in programs. ! Embraces full set of modern abstractions. Caveat.

1.1 Your First Program

PROGRAMMING STYLE. Fundamentals of Computer Science I

CS 11 java track: lecture 1

Conditionals, Loops, and Style

Introduction to Java. Java Programs Classes, Methods, and Statements Comments Strings Escape Sequences Identifiers Keywords

Programming with Java

Class 1: Homework. Intro to Computer Science CSCI-UA.0101 New York University Courant Institute of Mathematical Sciences Fall 2017

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

Lecture 1 - Introduction (Class Notes)

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

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

1.1 Your First Program! Naive ideal. Natural language instructions.

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

Software and Programming 1

Lecture 2: Intro to Java

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

COMP 110 Project 1 Programming Project Warm-Up Exercise

Lab # 2. For today s lab:

Debugging [continued]

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 2: SEP. 8TH INSTRUCTOR: JIAYIN WANG

Laboratory 1: Eclipse and Karel the Robot

COMP-202: Foundations of Programming. Lecture 2: Java basics and our first Java program! Jackie Cheung, Winter 2016

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

Goals. Java - An Introduction. Java is Compiled and Interpreted. Architecture Neutral & Portable. Compiled Languages. Introduction to Java

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

What did we talk about last time? Examples switch statements

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

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

1.1 Your First Program

1/16/12. CS 112 Introduction to Programming. A Foundation for Programming. (Spring 2012) Lecture #4: Built-in Types of Data. The Computer s View

COMP-202: Foundations of Programming. Lecture 2: Java basics and our first Java program! Jackie Cheung, Winter 2015

Software and Programming 1

Repetition with for loops

Using Karel with Eclipse

Object-oriented programming in...

Assignment Marking Criteria

6.170 Laboratory in Software Engineering Java Style Guide. Overview. Descriptive names. Consistent indentation and spacing. Page 1 of 5.

Java Programming Tutorial 1

Introduction Basic elements of Java

Full file at

Errors. Lecture 6. Hartmut Kaiser hkaiser/fall_2011/csc1254.html

CS125 : Introduction to Computer Science. Lecture Notes #4 Type Checking, Input/Output, and Programming Style

Index. Course Outline. Grading Policy. Lab Time Distribution. Important Instructions

Overview. Lab 5 Methods and Parameters

Warmup : Name that tune!

Using Eclipse and Karel

int n = 10; int sum = 10; while (n > 1) { sum = sum + n; n--; } cout << "The sum of the integers 1 to 10 is " << sum << endl;

Computer Components. Software{ User Programs. Operating System. Hardware

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

4. Java Project Design, Input Methods

Java Style Guide. 1.0 General. 2.0 Visual Layout. Dr Caffeine

COMP-202: Foundations of Programming

BASICS.

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

A Foundation for Programming

COMP-202 Unit 4: Programming with Iterations

CSCI 161: Introduction to Programming I Lab 1b: Hello, World (Eclipse, Java)

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

3 CREATING YOUR FIRST JAVA APPLICATION (USING WINDOWS)

Lesson 04: Our First Java Program (W01D4

Chapter 2: Programming Concepts

Chapter 7. Iteration. 7.1 Multiple assignment

An overview of Java, Data types and variables

Lecture 5: Methods CS2301

Algorithms and Programming I. Lecture#12 Spring 2015

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Identifiers. Identifiers are the words a programmer uses in a program Some identifiers are already defined. Some are made up by the programmer:

Transcription:

Program Development Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright 2002 2010 2/17/11 7:35 AM!

A Foundation for Programming any program you might want to write objects functions and modules graphics, sound, and image I/O arrays conditionals and loops what you've done already Math primitive data types text I/O assignment statements 3

Program Development Program development. Creating a program and putting it to good use. Program development environment. Software to support cycle of editing, compiling, and executing programs. command line Dr. Java 4

Program Development in Java 0. Think about your problem. 1. Edit your program.! Use a text editor.! Result: a text file such as HelloWorld.java.! 2. Compile it to create an executable file.! Use the Java compiler! Result: a Java bytecode file file such as HelloWorld.class.! Mistake? Go back to 1 to fix and recompile. 3. Execute your program.! Use the Java runtime.! Result: your program s output.! Mistake? Go back to 1 to fix, recompile, and execute. 5

Program Development in Java (using command line) 1. Edit your program using any text editor. 2. Compile it to create an executable file. 3. Execute your program. editor running in virtual terminal virtual TV second terminal for commands 6

Program Development in Java (using command line) 1. Edit your program. 2. Compile it by typing javac HelloWorld.java at the command line. 3. Execute your program. creates HelloWorld.class! invoke Java compiler at command line 7

Program Development in Java (using command line) 1. Edit your program. 2. Compile it to create an executable file. 3. Execute by typing java HelloWorld at the command line. uses HelloWorld.class! invoke Java runtime at command line 8

Program Development in Java (using Dr. Java) 1. Edit your program using the built-in text editor. 2. Compile it to create an executable file. 3. Execute your program. text editor 9

Program Development in Java (using Dr. Java) 1. Edit your program. 2. Compile it by clicking the compile button. 3. Execute your program. compile button creates HelloWorld.class! 10

Program Development in Java (using Dr. Java) 1. Edit your program. 2. Compile it to create an executable file. 3. Execute by clicking the run button or using Interactions pane. Alternative 1: run button (ok if no args) both use HelloWorld.class! Alternative 2: interactions pane (to provide args) 11

A Short History 12

Program Development Environments: A Short History Historical context is important in computer science.! We regularly use old software.! We regularly emulate old hardware.! We depend upon old concepts and designs. First requirement in any computer system: program development. Widely-used methods:! Switches/lights.! Punched cards.! Terminal.! Editor/virtual terminal.! IDE. 1960 1970 1980 1990 2000 switches/lights punched card/tape editor/terminal editor/virtual terminal integrated development environment 13

Switches and Lights Use switches to enter binary program code, lights to read results. PDP-8, circa 1970 14

Punched Cards / Line Printer Use punched cards for program code, line printer for output. IBM System 360, circa 1975 15 15

Timesharing Terminal Use terminal for editing program, reading output, and controlling computer. VAX 11/780 circa 1977 VT-100 terminal Timesharing: allowed many people to simultaneously use a single machine. 16

Editor and Virtual Terminal on a Personal Computer Use an editor to create and make changes to the program text. Use a virtual terminal to invoke the compiler and run the executable code. Pros. Works with any language, useful for other tasks, used by pros. Cons. Good enough for large projects? 17

Integrated Development Environment Use a customized application for all program development tasks. Ex 1. DrJava.! Ideal for novices.! Easy-to-use language-specific tools. Ex 2. Eclipse.! Widely used by professionals.! Powerful debugging and style-checking tools.! Steep learning curve.! Overkill for short programs. 18

Lessons from Short History First requirement in any computer system: program development. Program development environment must support cycle of editing, compiling, and executing programs. Two approaches that have served for decades:! Editor and virtual terminal.! Integrated development environment. Xerox Alto 1978 Macbook Air 2008 19

Debugging Admiral Grace Murray Hopper 20

95% of Program Development Def. A bug is a mistake in a computer program. Programming is primarily a process of finding and fixing bugs. Good news. Can use computer to test program. Bad news. Cannot use computer to automatically find all bugs. profound idea [stay tuned] 21

95% of Program Development Debugging. Always a logical explanation.! What would the machine do?! Explain it to the teddy bear. You will make many mistakes as you write programs. It's normal. 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. 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 If I had eight hours to chop down a tree, I would spend six hours sharpening an axe. Abraham Lincoln 22

Debugging Example Factor. Given an integer N > 1, compute its prime factorization. 3,757,208 = 2 3! 7! 13 2! 397 98 = 2! 7 2 17 = 17 11,111,111,111,111,111 = 2,071,723! 5,363,222,357 Application. Break RSA cryptosystem (factor 200-digit numbers). 23

Debugging Example Factor. Given an integer N > 1, compute its prime factorization. Brute-force algorithm. For each putative factor i = 2, 3, 4,, check if N is a multiple of i, and if so, divide it out. 3757208/8 24

Debugging: 95% of Program Development Programming. A process of finding and fixing mistakes.! Compiler error messages help locate syntax errors.! Run program to find semantic and performance errors. check if i is a factor 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) StdOut.print(i + " ") n = n / i as long as i is a factor, divide it out this program has many bugs! 25

Debugging: Syntax Errors Syntax error. Illegal Java program.! Compiler error messages help locate problem.! Goal: no errors and a file named Factors.class. 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) StdOut.print(i + " ") n = n / i % javac Factors.java Factors.java:4: ';' expected for (i = 0; i < n; i++) ^ 1 error the first error 26

Debugging: Syntax Errors Syntax error. Illegal Java program.! Compiler error messages help locate problem.! Goal: no errors and a file named Factors.class. need to declare variable i 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) StdOut.print(i + " "); n = n / i; need terminating semicolons syntax (compile-time) errors 27

Debugging: Semantic Errors Semantic error. Legal but wrong Java program.! Run program to identify problem.! Add print statements if needed to produce trace. 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) StdOut.print(i + " "); n = n / i; % javac Factors.java % java Factors oops, no argument Exception in thread "main" java.lang.arrayindexoutofboundsexception: 0 at Factors.main(Factors.java:5) 28

Debugging: Semantic Errors Semantic error. Legal but wrong Java program.! Run program to identify problem.! Add print statements if needed to produce trace. 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) StdOut.print(i + " "); n = n / i; need to start at 2 because 0 and 1 cannot be factors % javac Factors.java % java Factors 98 Exception in thread "main" java.lang.arithmeticexeption: / by zero at Factors.main(Factors.java:8) 29

Debugging: Semantic Errors Semantic error. Legal but wrong Java program.! Run program to identify problem.! Add print statements if needed to produce trace. 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) StdOut.print(i + " "); n = n / i; indents do not imply braces % javac Factors.java % java Factors 13 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 infinite loop! 30

Debugging: The Beat Goes On Success. Program factors 98 = 2! 7 2.! But that doesn't mean it works for all inputs.! Add trace to find and fix (minor) 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) { StdOut.print(i + " "); n = n / i; % java Factors 98 2 7 7 % % java Factors 5 % java Factors 6 2 % need newline??? no output??? missing the 3 31

Debugging: The Beat Goes On Success. Program factors 98 = 2! 7 2.! But that doesn't mean it works for all inputs.! Add trace to find and fix (minor) 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) { StdOut.println(i + " "); n = n / i; StdOut.println("TRACE: " + i + " " + n); % java Factors 5 TRACE 2 5 TRACE 3 5 TRACE 4 5 % java Factors 6 2 TRACE 2 3 Aha! i loop should go up to n 32

Debugging: Success? Success. Program now seems to work. 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) { StdOut.print(i + " "); n = n / i; StdOut.println(); % java Factors 5 5 % java Factors 6 2 3 % java Factors 98 2 7 7 % java Factors 3757208 2 2 2 7 13 13 397 33

Debugging: Performance Error Performance error. Correct program, but too slow. 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) { StdOut.print(i + " "); n = n / i; StdOut.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 -1-1 -1-1 -1-1 -1 very -1 long -1-1 wait (with a surprise ending) 34

Debugging: Performance Error Performance error. Correct program, but too slow. Solution. Improve or change underlying algorithm. fixes performance error: if n has a factor, it has one less than or equal to its square root public class Factors { public static void main(string[] args) { long n = Long.parseLong(args[0]); for (int i = 2; i <= n/i; i++) { while (n % i == 0) { StdOut.print(i + " "); n = n / i; StdOut.println(); % java Factors 98 2 7 7 % java Factors 11111111 11 73 101 % java Factors 11111111111111 11 239 4649 % java Factors 11111111111111111 2071723 missing last factor (sometimes) 35

Debugging: Performance Error Caveat. Optimizing your code tends to introduce bugs. Lesson. Don't optimize until it's absolutely necessary. public class Factors { public static void main(string[] args) { long n = Long.parseLong(args[0]); for (int i = 2; i <= n/i; i++) { while (n % i == 0) { StdOut.print(i + " "); n = n / i; if (n > 1) System.out.println(n); else System.out.println(); "corner case" need special case to print biggest factor (unless it occurs more than once) % java Factors 11111111 11 73 101 137 % java Factors 11111111111 21649 51329 % java Factors 11111111111111 11 239 4649 909091 % java Factors 11111111111111111 2071723 5363222357 36

Program Development: Analysis Q. How large an integer can I factor? % java Factors 3757208 2 2 2 7 13 13 397 % java Factors 9201111169755555703 9201111169755555703 after a few minutes of computing. largest factor digits (i <= N) 3 instant 6 0.15 seconds 9 77 seconds 12 21 hours 15 2.4 years (i <= N/i) instant instant instant 0.16 seconds 2.7 seconds 18 2.4 millennia 92 seconds estimated Note. Can't break RSA this way (experts are still trying). 37

Debugging Programming. A process of finding and fixing mistakes. 1. Create the program. 2. Compile it. Compiler says: That s not a legal program. Back to step 1 to fix syntax errors. 3. Execute it. Result is bizarrely (or subtly) wrong. Back to step 1 to fix semantic errors. 4. Enjoy the satisfaction of a working program! 5. Too slow? Back to step 1 to try a different algorithm. 38

Debugging is Hard Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. Brian Kernighan There are two ways of constructing a software design. One way is to make it so simple that there are obviously no deficiencies. And the other way is to make it so complicated that there are no obvious deficiencies. C. A. R. Hoare 39

Programming Style 40

Three Versions of the Same Program public class HelloWorld { public static void main(string[] args) { System.out.println("Hello, World"); /**********************************************************! * Compilation: javac HelloWorld.java! * Execution: java HelloWorld! *! * Prints "Hello, World".! * By tradition, this is everyone's first program.! *! * % java HelloWorld! * Hello, World! *! **********************************************************/! public class HelloWorld {! public static void main(string[] args) {! System.out.println("Hello, World");!!! public class HelloWorld { public static void main(string[] args) { System.out.println("Hello, World"); 41

Programming Style Different styles are appropriate in different contexts.! Booksite.! Textbook.! COS 126 assignment.! Java system libraries. Enforcing consistent style can:! Stifle creativity.! Confuse style rules with language rules. Emphasizing consistent style can:! Make it easier to spot errors.! Make it easier for others to read and use code.! Enable IDE to provide useful visual cues. 42

Naming Conventions Best practices.! Be consistent.! Choose descriptive variables names.! Obey Java conventions on upper/lowercase. purpose good bad worse factoring program Factors.java factors.java f.java is it a leap year? isleapyear leapyear _$1l1lO0O1 loop-index variable i ithtimethroughloop fred read an int from standard input readint() int() i() days per week DAYS_PER_WEEK DPW SEVEN 43

Whitespace Add whitespace to make your program more readable. 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) {! StdOut.print(i+" ");! n=n/i;!!!!! Best practices. 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) {! StdOut.print(i + " ");! n = n / i;!!!!! Best practices.! Be consistent.! One statement per line.! Space between binary operators. 44

Indenting Indent and add blank lines to reveal structure and nesting. 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) {! StdOut.print(i + " ");! n = n / i;!!!! 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) {! StdOut.print(i + " ");! n = n / i;!!!!! Best practices.! Be consistent.! 4 spaces per level of indentation.! Blank lines between logical blocks of code. 45

Comments Annotate what or why you are doing something, rather than how. // an end-of-line comment! /*************************************************! * A block comment draws attention! * to itself.! ************************************************/! Best practices.! Comment logical blocks of code.! Ensure comments agree with code.! Comment every important variable.! Comment any confusing code (or rewrite so that it's clear).! Include header that describe purpose of program, how to compile, how to execute, any dependencies, and a sample execution. COS 126 students: also name, precept, and login 46

Comments /*****************************************************************! * Compilation: javac Factors.java! * Execution: java Factors n! * Dependencies: StdOut.java! *! * Computes the prime factorization of n using brute force.! *! * % java Factors 4444444444! * 2 2 11 41 271 9091! *! *****************************************************************/! public class Factors {! public static void main(string[] args) {! // integer to be factored! long n = Long.parseLong(args[0]);! // for each potential factor i of n! for (long i = 2; i <= n; i++) {!!!! // if i is a factor of n, repeatedly divide it out! while (n % i == 0) {! StdOut.print(i + " ");! n = n / i;!! 47

Coding Standards De facto Java coding standard. http://www.oracle.com/technetwork/java/codeconvtoc-136057.html Less pedantic version of Sun standard. http://introcs.cs.princeton.edu/11style COS 126 students: follow these guidelines Automated tool to enforce coding standard. http://checkstyle.sourceforge.net used when you click "Check all Submitted Files" 48

U.S.S. Grace Murray Hopper 49