Computer Science 1. Basic Programming Concepts

151
R O B E R T S E D G E W I C K KEVIN W AYNE C omputer S cience An Interdisciplinary Approach 1. Basic Programming Concepts 1.1–1.2

Transcript of Computer Science 1. Basic Programming Concepts

R O B E R T S E D G E W I C K

KEVIN W A YNE

ComputerScience

An Interdisciplinary Approach

1. Basic Programming

Concepts

1.1–1.2

1. Basic Programming Concepts

• Why programming?

• Program development

• Built-in data types

• Type conversion

You need to know how to program

in order to be able to tell a computer what you want it to do.

Naive ideal: Natural language instructions.

Prepackaged solutions (apps) are great when what they do is what you want.

Programming enables you to make a computer do anything you want. well, almost anything (stay tuned)

“Please simulate the motion of N heavenly bodies, subject to Newton’s laws of motion and gravity.”

Ada LovelaceAnalytical

Engine

first computerfirst programmer

3

Programming: telling a computer what to do

Programming

• Is not just for experts.

• Is a natural, satisfying and creative experience.

•Enables accomplishments not otherwise possible.

•The path to a new worldof intellectual endeavor.

“ Instead of imagining that our main task is to instruct a

computer what to do, let us concentrate rather on explaining

to human beings what we want a computer to do. ”

− Don Knuth

Challenges

•Need to learn what computers can do.

•Need to learn a programming language. Telling a computer what to do

4

Telling a computer what to do

Police Squad Helps Dog Bite Victim.

Actual newspaper headlines

—Rich Pattis

Natural language

• Easy for human.

• Error-prone for computer.

Machine language

• Easy for computer.

• Error-prone for human.

High-level language

• Some difficulty for both.

• An acceptable tradeoff.

But which high-level language?

Naive ideal: A single programming language for all purposes.

for (int t = 0; t < 2000; t++)

{

a[0] = a[11] ^ a[9];

System.out.print(a[0]);for (int i = 11; i > 0; i--) a[i] =

a[i-1];

}

Simulating an LFSR (see Prologue lecture)

10: 8A00 RA ← mem[00]

11: 8B01 RB ← mem[01]

12: 1CAB RC ← RA + RB

13: 9C02 mem[02] ← RC

14: 0000 halt

5

Adding two numbers (see TOY lecture)

Our Choice: Java

Java features

•Widely used.

•Widely available.

•Continuously under development since early 1990s.

•Embraces full set of modern abstractions.

•Variety of automatic checks for mistakes in programs.James Gosling

Java economy

•Mars rover.

•Cell phones.

•Blu-ray Disc.

•Web servers.

•Medical devices.

•Supercomputing.

•…

millions of developers billions of devices

6

Our Choice: Java

Java features

•Widely used.

•Widely available.

•Continuously under development since early 1990s.

•Embraces full set of modern abstractions.

•Variety of automatic checks for mistakes in programs.

Facts of life

•No language is perfect.

•You need to start with some language.

Our approach

•Use a minimal subset of Java.

•Develop general programming skills that are applicable to many languages.

It’s not about the language!

“ There are only two kinds of

programming languages: those

people always [gripe] about and

those nobody uses.”

− Bjarne Stroustrup

8

A rich subset of the Java language vocabulary

built-in types

int

long

double

char

String

boolean

flow control

if

else

for

while

boolean operations

true

false

!

&&

||

Stringoperations

+

""

length()

charAt()

compareTo()

matches()

punctuation

{

}

(

)

,

;

assignment

=

arrays

a[]

length

new

object oriented

static

class

public

private

new

final

toString()

main()

Mathmethods

Math.sin()

Math.cos()

Math.log()

Math.exp()

Math.pow()

Math.sqrt()

Math.min()

Math.max()

Math.abs()

Math.PI

Systemmethods

System.print()

System.println()

System.printf()

type conversion methods

Integer.parseInt()

Double.parseDouble()

Your programs will primarily consist of these plus identifiers (names) that you make up.

operations on numeric types

+

-

/

%

++

--

comparisons

<

<=

>

>=

==

!=

our Std methods

StdIn.read ()

StdOut.print ()

StdDraw. ()

StdAudio. ()

StdRandom. ()

8

Anatomy of your first program

public class HelloWorld

{

public static void main(String[] args)

{

System.out.println("Hello, World");

}

}

text file named

HelloWorld.java

program name

main()method

body of main()(a single statement)

9

Anatomy of your next several programs

public class MyProgram

{

public static void main(String[] args)

{

...

}

}

main()methodtext file named

MyProgram.java

program name

body of main()(a sequence of statements)

10

Pop quiz on "your first program"

Q. Use common sense to cope with the following error messages.

% javac MyProgram.java

% java MyProgram

Main method not public.

% javac MyProgram.javaMyProgram.java:3: invalid method declaration; return type required public

static main(String[] args)

^

11

Pop quiz on "your first program"

Q. Use common sense to cope with the following error messages.

% javac MyProgram.java

% java MyProgram

Main method not public.

% javac MyProgram.javaMyProgram.java:3: invalid method declaration; return type required public

static main(String[] args)

^

12

A. Must have forgotten “public”. public static void main(String[] args)

A. Check HelloWorld. Aha! Forgot “void”. public static void main(String[] args)

Three versions of the same program.

14

/*************************************************************************

* 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"); } }

public class HelloWorld

{

public static void main(String[] args)

{

System.out.println("Hello, World");

}

}

Lesson: Fonts, color, comments, and extra space are not relevant in Java language.

6 Elements of Programming

% javac HelloWorld.java% java HelloWorld

Hello, World

PROGRAM 1.1.1 IS AN EXAMPLE OF a complete Java program. Its name is HelloWorld,

which means that its code resides in a file named HelloWorld.java (by convention in

Java). The program’s sole action is to print a message back to the terminal win-

dow. For continuity, we will use some standard Java terms to describe the program,

but we will not define them until later in the book: PROGRAM 1.1.1 consists of a single

class named HelloWorld that has a single method named main(). This method uses

two other methods named System.out.print() and System.out.println() to do the

job. (When referring to a method in the text, we use () after the name to

distinguish it from other kinds of names.) Until SECTION 2.1, where we learn about

classes that define multiple methods, all of our classes will have this same structure.

For the time being, you can think of “class” as meaning“program.”

The first line of a method specifies its name and other information; the rest is

a sequence of statements enclosed in braces and each followed by a semicolon. For

the time being, you can think of “programming” as meaning “specifying a class

Program 1.1.1Hello, World

public class HelloWorld{

public static void main(String[] args){

System.out.print("Hello, World");

System.out.println();

}}

This code is a Java program that accomplishes a simple task. It is traditionally a beginner’s first

program. The box below shows what happens when you compile and execute the program. The

terminal application gives a command prompt (% in this book) and executes the commands

that you type (javac and then java in the example below). The result in this case is that the

program prints a message in the terminal window (the third line).

Note on program style

Different styles are appropriate in different contexts.

• Integrated development environment

•Booksite

•Book

•Your code

Enforcing consistent style can

•Stifle creativity.

•Confuse style with language.

Emphasizing consistent style can

•Make it easier to spot errors.

•Make it easier for others to read and use code.

•Enable development environment to provide visual cues.

Bottom line for you: Listen to the person assigning your grade.

15or your boss!

Image sources

http://commons.wikimedia.org/wiki/File:KnuthAtOpenContentAlliance.jpg

http://commons.wikimedia.org/wiki/File:Ada_Lovelace.jpg

http://commons.wikimedia.org/wiki/File:Babbages_Analytical_Engine,_1834-1871._(9660574685).jpg

http://commons.wikimedia.org/wiki/File:James_Gosling_2005.jpg

http://commons.wikimedia.org/wiki/File:Bjarne-stroustrup.jpg

http://blog-images.muddymatches.co.uk.s3.amazonaws.com/dating-advice/wp-content/uploads/2013/01/Bad-guy.jpg

1. Basic Programming Concepts

• Why programming?

• Program development

• Built-in data types

• Type conversion

Program development in Java

is a three-step process, with feedback

1. EDIT your program

•Create it by typing on your computer's keyboard.

•Result: a text file such as HelloWorld.java.

3. RUN your program

•Use the Java runtime.

•Result: your program’s output.

•Mistake? Go back to 1. to fix, recompile, and run.

a legal Java program that does the wrong thing

2. COMPILE it to create an executable file

•Use the Java compiler

•Result: a Java bytecode file such as HelloWorld.class

•Mistake? Go back to 1. to fix and recompile.

not a legal Java program

EDIT

COMPILE

17

RUN

Software for program development

Any creative process involves cyclic refinement/development.

A significant difference with programs: We can use our computers to facilitate the process.

Program development environment: Software for editing, compiling and running programs.

Integrated development environment

•Often language- or system-specific.

•Can be helpful to beginners.

Bottom line: Variety of useful tools.

Virtual terminals

• Same for many languages and systems.

• Effective even for beginners.

Bottom line: Extremely simple and concise.

Two time-tested options: (Stay tuned for details).

COMPOSE

PLAYREHEARSE

EDIT

COMPILE RUN

18

Program development environments: a very 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.

Widely-used methods for program development

•switches and lights

•punched cards/compiler/runtime

•editor/compiler/runtime/terminal

•editor/compiler/runtime/virtual terminal

• integrated development environment

1960

1970

1980

1990

2000

19

Program development with switches and lights

Circa 1970: Use switches to input binary program code and data, lights to read output.

Stay tuned for details [lectures on the "TOY machine"].

PDP-8, circa 1970

switches

lights

20

Program development with punched cards and line printers

Mid 1970s: Use punched cards to input program code and data, line printer for output.

IBM System 360, circa 1975

22

Ask your parents about the "computer center" for details.

Timesharing allowed many users to share the same computer.

Program development with timesharing terminals

Late 1970s: Use terminal for editing program, reading output, and controlling computer.

VAX 11/780 circa 1977

VT-100 terminal

22

Program development with personal computers (one approach)

1980s to present day: Use multiple virtual terminals to interact withcomputer.

•Edit your program using any text editor in a virtual terminal.

•Compile it by typing javac HelloWorld.javain another virtual terminal.

•Run it by typing java HelloWorld

virtual terminal for editor

virtual TV set

virtual terminal to compile, run and examine output

invoke Java compiler at command line

invoke Java runtime at command line

23

Program development with personal computers (another approach)

pseudo-command line

1980s to present day: Use a customized application for program development tasks.

•Edit your program using the built-in texteditor.

•Compile it by clicking the “compile” button.

•Run it by clicking the “run” button or using the pseudo-command line.

“compile” button

“run” button

“Integrated Development Environment” (IDE)

http://drjava.org

24

Software for program development: tradeoffs

Pros

• Easy-to-use language-specific tools.

• System-independent (in principle).

• Used by professionals.

• Can be helpful to beginners.

Pros

• Approach works with any language.

• Useful beyond programming.

• Used by professionals.

• Has withstood the test of time.

Cons

• Overkill for short programs?

• Big application to learn and maintain.

• Often language- or system-specific.

Cons

• Good enough for long programs?

• Dealing with independent applications.

• Working at too low a level?

This course: Used in lectures/book.

IDE

Recommended for assignments.

Virtual terminals

25

Lessons from short history

Every computer has a program development environment that allows us to

•EDIT programs.

•COMPILE them to create an executable file.

•RUN them and examine theoutput.

Two approaches that have served for decades and are still effective:

•multiple virtual terminals.

Apple Macintosh 1984IBM PC 1990s

Macbook Air 2014

Wintel ultrabooks 2010sXerox Alto 1978

26

Image sources

http://commons.wikimedia.org/wiki/Category:2013_Boston_Red_Sox_season#mediaviewer/

File:Koji_Uehara_2_on_June_15,_2013.jpg

http://thenationalforum.org/wp-content/uploads/2011/03/Legendary-Musicians.png

http://pixabay.com/p-15812/?no_redirect

1. Basic Programming Concepts

• Why programming?

• Program development

• Built-in data types

• Type conversion

Built-in data types

29

A data type is a set of values and a set of operations on those values.

type set of values examples of values examples of operations

char characters'A'

'@'compare

String sequences of characters"Hello World"

"CS is fun"concatenate

int integers17

12345add, subtract, multiply, divide

double floating-point numbers3.1415

6.022e23add, subtract, multiply, divide

boolean truth valuestrue

falseand, or, not

Java's built-in data types

Pop quiz on data types

30

Q. What is a data type?

Pop quiz on data types

31

Q. What is a data type?

A. A set of values and a set of operations on those values.

int a;

int b;

a = 1234;

b = 99;

int c = a + b;

Basic Definitions

combined declaration and assignment statement

A variable is a name that refers to a value.

A literal is a programming-language representation of avalue.

A declaration statement associates a variable with a type.

An assignment statement associates a value with a variable.

variables

literals

assignment statements

declaration statements

32

Variables, literals, declarations, and assignments example: exchange values

a = b;

b = t;

}

}

a b t

undeclared undeclared undeclared

int a = 1234; 1234 undeclared undeclared

int b = 99; 1234 99 undeclared

int t = a; 1234 99 1234

a = b; 99 99 1234

b = t; 99 1234 1234

public class Exchange

{

public static void main(String[] args)

{

int a = 1234;

int b = 99; int

t = a;

This code exchanges

the values of a and b.

A trace is a table of variable values after each statement.

33

Q. What does this program do?

A. No way for us to confirm that it does the exchange! (Need output, stay tuned).

Data type for computing with strings: String

values sequences of characters

typical literals "Hello, " "1 " " "

operation concatenate

operator +

Stringdata type

expression value

"Hi, " + "Bob" "Hi, Bob"

"1" + " 2 " + "1" "1 2 1"

"1234" + " + " + "99" "1234 + 99"

"1234" + "99" "123499"

white space

space characters

Typical use: Input and output.

Examples of Stringoperations (concatenation)

Important note:

Character interpretation depends on context!

character

Ex 1: plus signs "1234" + " + " + "99"

operator operator

"1234" + " + " + "99"Ex 2: spaces

white space

34

Example of computing with strings: subdivisions of a ruler

public class Ruler

{

public static void main(String[] args)

{

String ruler1 = "1";

String ruler2 = ruler1 + " 2 " + ruler1; String

ruler3 = ruler2 + " 3 " + ruler2; String ruler4

= ruler3 + " 4 " + ruler3;

System.out.println(ruler4);

}

}

ruler1 ruler2 ruler3 ruler4

undeclared undeclared undeclared undeclared

ruler1 = "1"; 1 undeclared undeclared undeclared

ruler2 = ruler1 + " 2 " + ruler1; 1 1 2 1 undeclared undeclared

ruler3 = ruler2 + " 3 " + ruler2; 1 1 2 1 1 2 1 3 1 2 1 undeclared

ruler4 = ruler3 + " 4 " + ruler3; 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1

all + ops are concatenation

% java Ruler

1 2 1 3 1 2 1 4 1 2 1 3 1 2 1

1 2 1 3 1 2 1 4 1 2 1 3 1 2 1

35

Input and output

is necessary for us to provide data to our programs and to learn the result of computations.

Humans prefer to work with strings.

Programs work more efficiently with numbers.

Command-line input

• Strings you type after the program name are available as args[0], args[1], ... at run time.

• Q. How do we give an integer as command-line input?

• A. Need to call system method Integer.parseInt()to convert the strings to integers.

Stay tuned for many more options for input and output, and more details on type conversion.

command-line arguments

Output

• System.out.println()method prints the given string.

• Java automatically converts numbers to strings for output.

standard output

Bird's eye view of a Javaprogram

36

Input and output warmup: exchange values

public class Exchange

{

public static void main(String[] args)

{

int a = Integer.parseInt(args[0]); int b

= Integer.parseInt(args[1]); int t = a;

a = b;

b = t;

System.out.println(a);

System.out.println(b);

}

}

Q. What does this program do?

A. Reads two integers from the command line, then prints them out in the opposite order.

% java Exchange 5 2

2

5

% java Exchange 1234 99

99

1234

Java automatically converts intvalues to Stringfor output

38

Data type for computing with integers: int

values integers between −231 and 2 3 1−1

typical literals 1234 99 0 1000000

operations add subtract multiply divide remainder

operator + − / %

intdata type

expression value comment

5 + 3 8

5 - 3 2

5 3 15

5 / 3 1 drop fractional part

5 % 3 2 remainder

1 / 0 runtime error

Typical usage: Math calculations; specifying programs (stay tuned).

Examples of intoperations

expression value comment

3 5 - 2 13 has precedence

3 + 5 / 2 5 /has precedence

3 - 5 - 2 -4 left associative

( 3 - 5 ) - 2 -4 better style

Precedence

Important note:

Only 232 different intvalues.

not quite the same as integers

38

Example of computing with integers and strings, with type conversion

public class IntOps

{

public static void main(String[] args)

{

int a = Integer.parseInt(args[0]); int b

= Integer.parseInt(args[1]); int sum =

a + b;

int prod = a b; int

quot = a / b; int

rem = a % b;

System.out.println(a + " + " + b + " = " + sum);

System.out.println(a + " " + b + " = " + prod);

System.out.println(a + " / " + b + " = " + quot);

System.out.println(a + " % " + b + " = " + rem);

}

}

% java IntOps 5 2

5 + 2 = 7

5 2 = 10

5 / 2 = 2

5 % 2 = 1

% java IntOps 1234 99

1234 + 99 = 1333

1234 99 = 122166

1234 / 99 = 12

1234 % 99 = 46

Note: 1234 = 12*99 + 46

Java automatically converts intvalues to Stringfor concatenation

39

Examples:

no doublevalue for π.

Data type for computing with floating point numbers: double

values real numbers

typical literals

operations

3.14159 2.0 1.4142135623730951 6.022e23

add subtract multiply divide remainder

operator

+

− /%

doubledata type

expression value

3.141 + .03 3.171

3.141 - .03 3.111

6.02e23/2 3.01e23

5.0 / 3.0 1.6666666666666667

10.0 % 3.141 0.577

Math.sqrt(2.0) 1.4142135623730951

Typical use: Scientific calculations.

Examples of doubleoperations

expression value

1.0 / 0.0 Infinity

Math.sqrt(-1.0) NaN

Special values

Typical double values are approximations

"not a number"

6.022 1023

no doublevalue for √

2

no doublevalue for 1/3.

40

Other built-in numeric types

shortdata type

values integers between −215 and 2 1 5−1

operations [ same as int ]

longdata type

values integers between −263 and 2 6 3−1

operations [ same as int ]

floatdata type

values real numbers

operations [ same as double ]

Why different numeric types?

•Tradeoff between memory use and range for integers.

•Tradeoff between memory use and precision for real numbers.

short

int, float

long, double

41

Excerpts from Java’s Math Library

public class Math

double abs(double a) absolute value of a

double max(double a, double b) maximum of aand b

double min(double a, double b) minimum of aand b

double sin(double theta) sine function

double cos(double theta) cosine function

double tan(double theta) tangent function

double exp(double a) exponential (ea)

double log(double a) natural log (loge a, or ln a)

double pow(double a, double b) raise a to the bth power (ab)

long round(double a) round to the nearest integer

double random() random number in [0. 1)

double sqrt(double a) square root of a

double E value of e (constant)

double PI value of π (constant)

also defined for

int, long, and float

inverse functions also available:

asin(), acos(), and atan()

Degrees in radians. Use toDegrees() and toRadians()) to convert.

You can discard your calculator now (please).

43

Example of computing with floating point numbers: quadratic equation

public class Quadratic

{public static void main(String[] args)

{

// Parse coefficients from command-line.

double b = Double.parseDouble(args[0]);

double c = Double.parseDouble(args[1]);

// Calculate roots of x x + b x + c. double

discriminant = b b - 4.0 c; double d =

Math.sqrt(discriminant); double root1 =

(-b + d) / 2.0; double root2 = (-b - d) /

2.0;

// Print them out.

System.out.println(root1);

System.out.println(root2);

}

}

% java Quadratic –3.0 2.0

2.0

1.0

% java Quadratic –1.0 –1.0

1.618033988749895

-0.6180339887498949

% java Quadratic 1.0 1.0

NaN

NaN

% java Quadratic 1.0 hello

java.lang.NumberFormatException: hello

% java Quadratic 1.0

java.lang.ArrayIndexOutOfBoundsException

From algebra: the roots of x2 + bx + c are —b ±

,b 2 —4c

2

x2— 3x + 2

x2 x 1

x2 + x+ 1

Need two arguments.

(Fact of life: Not all error messages are crystal clear.)

43

Data type for computing with true and false: boolean

values true false

literals true false

operations and or not

operator && || !

booleandata type

Typical usage: Control logic and flow of a program (stay tuned).

Truth-table definitions

Proof

a !a a b a && b a || b

true false false false false false

false true false true false true

true false false true

true true true true

Q. aXOR b?

A. (!a && b) || (a && !b)

a b !a && b a && !b (!a && b) || (a && !b)

false false false false false

false true true false true

true false false true true

true true false false false

Recall first lecture

44

Comparison operators

Fundamental operations that are defined for each primitive type allow us to compare values.

•Operands: two expressions of the same type.

•Result: a value of type boolean.

operator meaning true false

== equal 2 == 2 2 == 3

!= not equal 3 != 2 2 != 2

< less than 2 < 13 2 < 2

<= less than or equal 2 <= 2 3 <= 2

> greater than 13 > 2 2 < 13

>= greater than or equal 3 >= 2 2 >= 3

non-negative discriminant? ( b b - 4.0 a c ) >= 0.0

beginning of a century? ( year % 100 ) == 0

legal month? ( month >= 1 ) && ( month <= 12 )

Examples

Typical double values are

approximations so beware

of == comparisons

45

Example of computing with booleans: leap year test

public class LeapYear{

public static void main(String[] args)

{int year = Integer.parseInt(args[0]);

boolean isLeapYear;

// divisible by 4 but not 100isLeapYear = (year % 4 == 0) && (year % 100 != 0);

// or divisible by 400

isLeapYear = isLeapYear || (year % 400 == 0);

System.out.println(isLeapYear);}

}

% java

true

LeapYear 2016

% java

false

LeapYear 1993

% java

false

LeapYear 1900

% java

true

LeapYear 2000

46

Q. Is a given year a leap year?

A. Yes if either (i) divisible by 400 or (ii) divisible by 4 but not 100.

Image sources

http://commons.wikimedia.org/wiki/File:Calculator_casio.jpg

1. Basic Programming Concepts

• Why programming?

• Program development

• Built-in data types

• Type conversion

Type checking

Types of variables involved in data-type operations always must match the definitions.

When appropriate, we often convert a value from one type to another to make types match.

The Java compiler is your friend : it checks for type errors in your code.

public class BadCode

{public static void main(String[] args)

{

String s = "123" 2;

}

}

% javac BadCode.java

BadCode.java:5: operator cannot be applied to java.lang.String,int String

s = "123" 2;

^

1 error

49

Type conversion with built-in types

Type conversion is an essential aspect of programming.

Type conversion can give counterintuitive results but gets easier to understand with practice

Pay attention to the type of your data.

Automatic

•Convert number to string for "+".

•Make numeric types match if no loss of precision.

Explicitly defined for function call.

Cast for values that belong to multiple types.

•Ex: small integers can be short, intor long.

•Ex: doublevalues can be truncated to intvalues.

expression type value

"x: " + 99 String "x: 99"

11 0.25 double 2.75

Integer.parseInt("123") int 123

Math.round(2.71828) long 3

(int) 2.71828 int 2

(int) Math.round(2.71828) int 3

11 (int) 0.25 int 0

50

Pop quiz on type conversion

Q. Give the type and value of each of the following expressions.

a. ( 7 / 2 ) 2.0

b. ( 7 / 2.0 ) 2

51

c. "2" + 2

d. 2.0 + "2"

Pop quiz on type conversion

Q. Give the type and value of each of the following expressions.

a. ( 7 / 2 ) 2.0

b. ( 7 / 2.0 ) 2

52

c. "2" + 2

d. 2.0 + "2"

6.0, a double(7/2 is 3, an int)

7.0, a double

22, a String

2.02, a String

An instructive story about type conversion

Why different numeric types?

•Tradeoff between memory use and range for integers.

•Tradeoff between memory use and precision for floating-point.

short int,

float long,

double

What to do with an impossible conversion?

•Approach 1: Avoid doing it in the firstplace.

•Approach 2 (Java): Live with a well-defined result.

•Approach 3: Crash.

A conversion may be impossible.

•Example: (short) 70000.

• Short values must be between −21 5 and 215 − 1= 32767 .

First launch of Ariane 5, 199653

Example of type conversion put to good use: pseudo-random integers

public class RandomInt

{

public static void main(String[] args)

{

int N = Integer.parseInt(args[0]);

double r = Math.random();

int t = (int) (r N);

% java RandomInt 6

3

% java RandomInt 6

0

% java RandomInt 10000

3184

System method Math.random()returns a pseudo-random doublevalue in [0, 1).

Stringto int(system method)

doubleto int(cast)

System.out.println(t);

}

}

intto double(automatic)

54

Problem: Given N, generate a pseudo-random integer between 0 and N − 1.

Summary

A data type is a set of values and a set of operations on those values.

Commonly-used built-in data types in Java

• String, for computing with sequence of characters, for input and output.

• int, for computing with integers, for math calculations in programs.

• double, for computing with floating point numbers, typically for science and math apps.

• boolean, for computing with true and false, for decision making in programs.

In Java you must:

•Declare the types of your variables.

•Convert from one type to another when necessary.

•Identify and resolve type errors in order to compile your code.

Pay attention to the type of your data.

The Java compiler is your friend : it will help you identify and fix type errors in your code.

55

2. Conditionals and loops

2. Conditionals & Loops

• Conditionals: the ifstatement

• Loops: the whilestatement

• An alternative: the for loop

• Nesting

• Debugging

Context: basic building blocks for programming

any program you might want to write

objects

functions and modules

graphics, sound, and image I/O

arrays

conditionals and loops

Math text I/O

assignment statementsprimitive data types

Previous lecture: equivalent to a calculator

This lecture:

to infinity and beyond!

conditionals and loops

3

Conditionals and Loops

Control flow

•The sequence of statements that are actually executed in a program.

•Conditionals and loops enable us to choreograph control flow.

statement 1

straight-line control flow

[ previous lecture ]

statement 2

statement 3

statement 4

boolean 1

control flow with conditionals and a loop

[this lecture]

statement 1

statement 2boolean 2

statement 3

false

true

false

true

4

The ifstatement

Execute certain statements depending on the values of certain variables.

•Evaluate a booleanexpression.

• If true, execute a statement.

•The elseoption: If false, execute a different statement.

Example: if (x < 0) x = -x;

x < 0 ?

x = -x;

true false

Replaces x with the absolute value of x

Example: if (x > y) max = x;

else max = y;

x > y ?

max = x;

true false

Computes the maximum of x and y

5

max = y;

Example of if statement use: simulate a coin flip

public class Flip

{

public static void main(String[] args)

{

if (Math.random() < 0.5)

System.out.println("Heads");

else

System.out.println("Tails");

}

}

% java Flip

Heads

% java Flip

Heads

% java Flip

Tails

% java Flip

Heads

6

public class TwoSort

{public static void main(String[] args){

int a = Integer.parseInt(args[0]); int b

= Integer.parseInt(args[1]); if (b < a)

{int t = a; a

= b;

b = t;}System.out.println(a);

System.out.println(b);

}

}

Q. What does this program do?

% java TwoSort 1234 99

99

1234

% java TwoSort 99 1234

99

1234

A. Reads two integers from the command line, then prints them out in numerical order.

Example of if statementuse: 2-sort

alternatives for if and elsecan be a sequence of

statements, enclosed in braces

7

Pop quiz on ifstatements

public class ThreeSort

{public static void main(String[] args){

int a = Integer.parseInt(args[0]); int b

= Integer.parseInt(args[1]); int c =

Integer.parseInt(args[2]);

System.out.println(a);

System.out.println(b);

System.out.println(c);

}

}

Q. Add code to this program that puts a, b, and c in numerical order.

% java ThreeSort 1234 99 1

1

99

1234

% java ThreeSort 99 1 1234

1

99

1234

8

Pop quiz on ifstatements

public class ThreeSort

{public static void main(String[] args){

int a = Integer.parseInt(args[0]); int b

= Integer.parseInt(args[1]); int c =

Integer.parseInt(args[2]); if (b < a)

{ int t = a; a = b; b = t; } if (c

< a)

{ int t = a; a = c; c = t; } if (c

< b)

{ int t = b; b = c; c = t; }

System.out.println(a);

System.out.println(b);

System.out.println(c);

}

}

Q. Add code to this program that puts a, b, and c in numerical order.

% java ThreeSort 1234 99 1

1

99

1234

% java ThreeSort 99 1 1234

1

99

1234

A.makes a smaller

than b

makes a smaller than both b and c

makes b smaller than c

9

Example of if statement use: error checks

if (b == 0) System.out.println("Division by zero");

else System.out.println(a + " / " + b + " = " + a / b);

public class IntOps

{

public static void main(String[] args)

{

int a = Integer.parseInt(args[0]); int b

= Integer.parseInt(args[1]); int sum =

a + b;

int prod = a b;

System.out.println(a + " + " + b + " = " + sum);

System.out.println(a + " " + b + " = " + prod);

if (b == 0) System.out.println("Division by zero");

else System.out.println(a + " % " + b + " = " + a % b);

}

}

% java IntOps 5 2

5 + 2 = 7

5 2 = 10

5 / 2 = 2

5 % 2 = 1

% java IntOps 5 0

5 + 0 = 5

5 0 = 0

Division by zero

Division by zero

10

Good programming practice. Use conditionals to check for and avoid runtime errors.

Image sources

http://commons.wikimedia.org/wiki/File:Calculator_casio.jpg

http://en.wikipedia.org/wiki/File:Buzz-lightyear-toy-story-3-wallpaper.jpg

http://www.ncbi.nlm.nih.gov/pmc/articles/PMC2789164/#!po=30.0000 [181e306f1.jpg]

R O B E R T S E D G E W I C K

KEVIN W A YNE

ComputerScience

An Interdisciplinary Approach

2. Conditionals and loops

2. Conditionals & Loops

• Conditionals: the ifstatement

• Loops: the whilestatement

• An alternative: the for loop

• Nesting

• Debugging

The while loop

Execute certain statements repeatedly until certain conditions are met.

•Evaluate a booleanexpression.

• If true, execute a sequence of statements.

•Repeat.

falseExample:

int i = 0;

int v = 1;

while (i <= n)

{

System.out.println(v); i

= i + 1;

v = 2 v;

}

Prints the powers of two from 20 to 2n .

[stay tuned for a trace]

i <= n ?

i = 0;

true

v = 1;

System.out.println(v);

i = i + 1;

v = 2 v;

3

Example of while loop use: print powers of two

A trace is a table of variable values after each statement.

i v i <= n

0 1 true

1 2 true

2 4 true

3 8 true

4 16 true

5 32 true

6 64 true

7 128 false

% java PowersOfTwo 6

1

2

4

8

16

32

64

public class PowersOfTwo

{

public static void main(String[] args)

{

int n = Integer.parseInt(args[0]); int i

= 0;

int v = 1; while

(i <= n)

{

System.out.println(v); i

= i + 1;

v = 2 v;

}

}

}

Prints the powers of two from 20 to 2n .

4

Pop quiz on while loops

Q. Anything wrong with the following code?

public class PQwhile

{

public static void main(String[] args)

{

int n = Integer.parseInt(args[0]); int i

= 0;

int v = 1; while

(i <= n)

System.out.println(v); i

= i + 1;

v = 2 v;

}

}

5

Pop quiz on while loops

Q. Anything wrong with the following code?

public class PQwhile

{

public static void main(String[] args)

{

int n = Integer.parseInt(args[0]); int i

= 0;

int v = 1; while

(i <= n)

System.out.println(v); i

= i + 1;

v = 2 v;

}

}

Q. What does it do (without the braces)?

A. Goes into an infinite loop.

A. Yes! Needs braces.

{

}

% java PQwhile 6

1

1

1

1

1

1

1

1

1

1

challenge: figure out

how to stop it

on your computer

6

Example of while loop use: implementMath.sqrt()

Goal. Implement square root function.

i ti 2/ti average

0 2 1 1.5

1 1.5 1.3333333 1.4166667

2 1.4166667 1.4117647 1.4142157

3 1.4142157 1.4142114 1.4142136

4 1.4142136 1.4142136

computing the square root of 2 to seven places

Newton-Raphson method to compute √c

• Initialize t0 = c. if t = c/t then t2 = c

• Repeat until ti = c/ti (up to desired precision):

Set ti+1 to be the average of ti and c /ti.

% java Sqrt 60481729.0

7777.0

% java Sqrt 2.0

1.4142136

7

Example of while loop use: implementMath.sqrt()

Newton-Raphson method to compute √c

• Initialize t0 = c.

• Repeat until ti = c/ti (up to desired precision):

Set ti+1 to be the average of ti and c /ti.

% java Sqrt 60481729.0

7777.0

% java Sqrt 2.0

1.41421356237309

5

Isaac Newton

1642-1727

Scientists studied

computation well before

the onset of the computer.

public class Sqrt

{

public static void main(String[] args)

{

double EPS = 1E-15; error tolerance (15 places)

double c = Double.parseDouble(args[0]); double

t = c;

while (Math.abs(t - c/t) > t EPS) t =

(c/t + t) / 2.0;

System.out.println(t);

}

}

8

Newton-Raphson method

Explanation (some math omitted)

•Goal: find root of function f(x) (value of x for which f(x) = 0).

• Start with estimate t0.

• Draw line tangent to curve at x = ti .

• Set ti+1 to be x-coordinate where line hits x-axis.

•Repeat until desired precision.

use f(x) = x2 − c for √c

y = f (x)

titi+ 1ti+ 2

root: f(x) = 0

ti+ 3

9

Image sources

http://www.sciencecartoonsplus.com

http://en.wikipedia.org/wiki/Isaac_Newton

http://www.onlinemathtutor.org/help/wp-content/uploads/math-cartoon-28112009.jpg

2. Conditionals & Loops

• Conditionals: the ifstatement

• Loops: the whilestatement

• An alternative: the for loop

• Nesting

• Debugging

The for loop

An alternative repetition structure.

•Evaluate an initialization statement.

•Evaluate a boolean expression.

• If true, execute a sequence of statements,

then execute an increment statement.

•Repeat.

Example:

int v = 1;

for ( int i = 0; i <= n; i++ )

{

System.out.println( i + " " + v ); v = 2

v;

}

Prints the powers of two from 20 to 2n

Every forloop has an equivalent while loop:

int v = 1;

int i = 0;

while ( i <= n; )

{

System.out.println( i + " " + v ); v = 2

v;

i++;

}

Why? Can provide code that is more compact and understandable.

initialization statement

boolean expression

increment statement

12

Examples of forloop use

int sum = 0;for (int i = 1; i <= N; i++) sum

+= i;

System.out.println(sum);

Compute sum (1 + 2 + 3 + . . . + N)

sum i

1 1

3 2

6 3

10 4

trace at end of loop for N = 4

long product = 1;for (int i = 1; i <= N; i++)

product = i;

System.out.println(product);

Compute N! = 1 * 2 * 3 * . . . * N

for (int k = 0; k <= N; k++) System.out.println(k + " "

+ 2 Math.PI k/N);

Print a table of function values

product i

1 1

2 2

6 3

24 4

trace at end of loop for N = 23

int v = 1;while (v <= N/2)

v = 2 v;

System.out.println(v);

Print largest power of 2 less than or equal to N

v

2

4

8

16

k

0 0

1 1.57079632...

2 3.14159265...

3 4.71238898...

4 6.28318530...

2nk

U

13

24

Example of for loop use: subdivisions of a ruler

Create subdivisions of a ruler to 1/N inches.

• Initialize rulerto one space.

•For each value ifrom 1to N:

sandwich ibetween two copies of ruler.

public class Ruler

{

public static void main(String[] args)

{int N = Integer.parseInt(args[0]);

String ruler = " ";

for (int i = 1; i <= N; i++) ruler

= ruler + i + ruler;

System.out.println(ruler);

}

}

2100 − 1 integers in output (!)

% java Ruler 100Exception in thread "main"

java.lang.OutOfMemoryError

java Ruler 4

1 2 1 3 1 2 1 4 1 2 1 3 1 2 1

1 2 1 3 1 2 1 4 1 2 1 3 1 2 1

i ruler

1 " 1 "

2 " 1 2 1 "

3 " 1 2 1 3 1 2 1 "

4 " 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 "

End-of-loop trace

Note: Small program can produce huge amount of output.

Pop quiz on for loops

Q. What does the following program print?

public class PQfor

{

public static void main(String[] args)

{

int f = 0, g = 1;

for (int i = 0; i <= 10; i++)

{

System.out.println(f); f

= f + g;

g = f - g;

}

}

}

15

Pop quiz on for loops

Q. What does the following program print?

public class PQfor

{

public static void main(String[] args)

{

int f = 0, g = 1;

for (int i = 0; i <= 10; i++)

{

System.out.println(f); f

= f + g;

g = f - g;

}

}

}

A. i f g

0 0 1

1 1 0

2 1 1

3 2 1

4 3 2

5 5 3

6 8 5

7 13 8

8 21 13

9 34 21

10 55 34

Beginning-of-loop trace

values printed

16

R O B E R T S E D G E W I C K

KEVIN W A YNE

ComputerScience

An Interdisciplinary Approach

2. Conditionals and loops

2. Conditionals & Loops

• Conditionals: the ifstatement

• Loops: the whilestatement

• An alternative: the for loop

• Nesting

• Debugging

Nesting conditionals and loops

Nesting

•Any “statement” within a conditional or loop

may itself be a conditional or a loop statement.

•Enables complex control flows.

•Adds to challenge of debugging.

if-elsestatement

within a whileloop

within a forloop

[ Stay tuned for an explanation of this code. ]

3

for (int t = 0; t < trials; t++)

{

int cash = stake;

while (cash > 0 && cash < goal)

if (Math.random() < 0.5) cash++;

else cash--;

if (cash == goal) wins++;

}

Example:

47450) rate = 0.22;if (income < else

{if (income < 114650) rate = 0.25; else

{if (income < 174700) rate = 0.28; else

{if (income < 311950) rate = 0.33; else rate = 0.35;

}}

}

Example of nesting conditionals: Tax rate calculation

ifstatement

within an ifstatement within an ifstatement

ifstatement

within an ifstatement

ifstatement

within an if statementwithin an if statementwithin an ifstatement

4

Goal. Given income, calculate proper tax rate.

income rate

0 – $47,450 22%

$47,450 – $114,649 25%

$114,650 – $174,699 28%

$174,700 – $311,949 33%

$311,950 + 35%

Pop quiz on nested ifstatements

Q. Anything wrong with the following code?

public class PQif

{

public static void main(String[] args)

{

double income = Double.parseDouble(args[0]);

double rate = 0.35;

if (income < 47450) rate = 0.22; if

(income < 114650) rate = 0.25; if

(income < 174700) rate = 0.28; if

(income < 311950) rate = 0.33;

System.out.println(rate);

}

}

5

Pop quiz on nested ifstatements

Q. Anything wrong with the following code?

A. Yes! Need elseclauses. Without them, code is equivalent to:

public class PQif

{

public static void main(String[] args)

{

double income = Double.parseDouble(args[0]);

double rate = 0.35;

if (income < 47450) rate = 0.22; elseif (income < 114650) rate = 0.25; else if

(income < 174700) rate = 0.28; else if

(income < 311950) rate =0.33;

System.out.println(rate);

}

}

Note. Braces are not needed in this

case, but BE CAREFUL when nesting

if-else statements because of

potential ambiguity (see Q&A p. 75).

if (income < 311950) rate = 0.33;

else rate = 0.35;

6

Gambler's ruin problem

A gambler starts with $stake and places $1 fair bets.

•Outcome 1 (loss): Gambler goes broke with $0.

•Outcome 2 (win): Gambler reaches$goal.

One approach: Monte Carlo simulation.

•Use a simulated coin flip.

•Repeat and compute statistics.

Q. What are the chances of winning?

Q. How many bets until win or loss?

7

public class Gambler{

public static void main(String[] args){

int stake = Integer.parseInt(args[0]); intgoal = Integer.parseInt(args[1]); int trials =Integer.parseInt(args[2]);

int wins = 0;for (int t = 0; t < trials; t++){

int cash = stake;while (cash > 0 && cash < goal){

if (Math.random() < 0.5) cash++; else cash--;

}if (t == goal) wins++;

}System.out.println(wins + " wins of " + trials);

}}

Example of nesting conditionals and loops: Simulate gamber's ruin

Gambler's ruin simulation

• Get command-line arguments.

• Run all the experiments.

• Run one experiment.

• Make one bet.

• If goal met, count the win.

• Print #wins and # trials.

forloop

while loop within a for loop

if statement

within a while loop within a for loop

% java Gambler 5 25 1000

191 wins of 1000

8

Digression: simulation and analysis

Facts (known via mathematical analysis for centuries)

•Probability of winning = stake ÷ goal.

•Expected number of bets = stake × desired gain.

% java Gambler

191 wins of 1000

5 25 1000

% java Gambler

203 wins of 1000

5 25 1000

% java Gambler 500 2500 1000

197 wins of 1000

Christiaan Huygens

1629-1695

Early scientists were

fascinated by the study

of games of chance.

500/2500 = 20%

500*(2500 - 500) = 1,000,000

Example

• 20% chance of turning $500 into $2500.

• Expect to make 1 million $1 bets.

Remarks

•Computer simulation can help validate mathematical analysis.

•For this problem, mathematical analysis is simpler (if you know the math).

•For more complicated variants, computer simulation may be the best plan of attack.

stake goal trials

uses about 1 billion coin flips

9

Image sources

http://pixabay.com/en/atlantic-city-ocean-holiday-316301/

http://en.wikipedia.org/wiki/Christiaan_Huygens#mediaviewer/File:Christiaan_Huygens.jpg

2. Conditionals & Loops

• Conditionals: the ifstatement

• Loops: the whilestatement

• An alternative: the for loop

• Nesting

• Debugging

COMPUTER SCIENCES E D G E W I C K / W A Y N E

PARTI : P RO G RA M M I N G I N JAVA

CS.2.E.Loops.Debugging

Debugging

is 99% of program development in any programming language, even for experts.

Impossible ideal: "Please compile, execute, and debug my program."

Bottom line: Programming is primarily a process of finding and fixing mistakes.

“ 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

You will make many mistakes as you write programs. It's normal.

Bug: A mistake in a program.

Why is this impossible? Stay tuned.

EDIT

COMPILE RUN

Debugging: The process of eliminating bugs.

12

Debugging

is challenging because conditionals and loops dramatically increase the number of possible outcomes.

Most programs contain numerous conditionals and loops, with nesting.

program structure no loops n conditionals 1 loop

number of possible execution

sequences 1 2n no limit

Good news. Conditionals and loops provide structure that helps us understand our programs.

“ The quality of programmers is a decreasing

function of the number of goto statements in

the programs they produce. ”

− Edsgar Dijkstra

Old and low-level languages have a goto

statement that provides arbitrary structure.

Eliminating gotos was controversial until

Edsgar Dijkstra published the famous note

"Goto considered harmful " in 1968.

13

Debugging a program: a running example

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

}

}

}

Method

•Consider each integer i less than n

•While i divides n evenly

Print i (it is a factor of n ).

Replace n with n/i .

Rationale:

1. Any factor of n/i is a factor of n.

2. i may be a factor of n/i.

Problem: Factor a large integer n.

Application: Cryptography.

Surprising fact: Security of internet commerce

depends on difficulty of factoring large integers.

3,757,208 = 2 2 2 7 13 13 397

98 = 2 7 7

17 = 17

11,111,111,111,111,111 = 2,071,723 5,363,222,357

This program has bugs!

14

Debugging a program: syntax errors

Is your program a legal Javaprogram?

•Java compiler can help you find out.

•Find the first compiler error (if any).

•Repeat.

•Result: An executable Factors.classfile

public class Factors

{

while (n % i == 0)

n = n / i

}

}

}

% javac Factors.java

Factors.java:5: ';' expected

long n = Long.parseLong(args[0])

^

...

System.out.print(i + " ");; need terminating

semicolons

public static void main(String[] args){

long n = Long.parseLong(args[0]);for ( inti = 0; i < n; i++)

{

need to declare type of i

% javac Factors.java Factors.java:6:

cannot find symbol symbol : variable i

location: class FactorsX

for ( i = 0; i < n; i++)

^

...

Trying to tell a computer what to do

This legal program still has bugs!% javac Factors.java

%

EDIT

COMPILE

15

Debugging a program: runtime and semantic errors

Does your legal Java program do what you want it to do?

•You need to run it to find out.

•Find the first runtime error (if any).

•Fix and repeat.

rspublic class Facto

{

public static void main(String[] args)

{

long n = Long.parseLong(args[0]);

0; i < n; i++)for ( int i =

{

}

}

}

while (n % i == 0)

{System.out.print(i + " "); n =

n / i;}

need braces

2

need to start at 2 since 0 and 1 are not factors

% java Factors 98

2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 22 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2

% java Factors 98

2 7 7% 98 = 2 × 7× 7 ✓

% javac Factors.java

% java Factors oops, need argument

Exception in thread "main"

java.lang.ArrayIndexOutOfBoundsException: 0

at Factors.main(Factors.java:5)

you will see this message!

This working program still has bugs!

% java Factors 98 Exception

in thread "main"

java.lang.ArithmeticException: / by zero at

Factors.main(Factors.java:8)

EDIT

COMPILE

16

RUN

Debugging a program: testing

Does your legal Java program always do what you want it to do?

•You need to test on many types of inputs it to find out.

•Add trace code to find the first error.

•Fix the error.

•Repeat.

% java Factors 5

??? no output

% java Factors 6

2 ??? where’s the 3?

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("TRACE " + i + " " + n);

}

}

}

% javac Factors.java% java Factors 5

TRACE 2 5

TRACE 3 5

TRACE 4 5% java Factors 6

2

TRACE 2 3

% java Factors 98

2 7 7% need newline

AHA! Need to print out n

(if it is not 1).

17

Debugging a program: testing

Does your legal Java program always do what you want it to do?

•You need to test on many types of inputs it to find out.

•Add trace code to find the first error.

•Fix the error.

•Repeat. 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;

}

}if (n > 1) System.out.println(n); else

System.out.println();

}

% java Factors 5

TRACE 2 5

TRACE 3 5

TRACE 4 5

% javac Factors.java% 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

???%$%@$#!!

forgot to recompile

Note: This working program} still has a bug (stay tuned).

18

Debugging a program: performance

N

{

while (n % i == 0)

{System.out.print(i + " "); n =

n / i;

}

}if (n > 1) System.out.println(n); else

System.out.println();

}

}

Method

less than N

Is your working Java program fast enough to solve your problem?

•You need to test it on increasing problem sizes to find out.

•May need to change the algorithm to fix it.

•Repeat.

might work,but way too slow

% java Factors 11111111

11 73 101 137

% java Factors 11111111111

21649 513239

% java Factors 11111111111111

11 239 4649 909091

% java Factors 11111111111111111

2071723 5363222357 immediate

public class Factors

{

public static void main(String[] args)

{

long n = Long.parseLong(args[0]); for

( int i = 2; i < =n/i; i++)

implement the change

change the algorithm: no need to check when

i·i >n since all smaller factors already checked

• Consider each integer i ≤n/i

•While i divides n evenly

print i (it is a factor of n )

replace n with n/i .

45

Debugging a program: performance analysis

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)

{System.out.print(i + " "); n =

n / i;

}}if (n > 1) System.out.println(n); else

System.out.println();

}

}

Q. How large an integer can I factor?

% java Factors 9201111169755555703

9201111169755555703

digits in largest factor

i < N i <= N/i

3 instant instant

6 instant instant

9 77 seconds instant

12 21 hours† instant

15 2.4 years† 2.7 seconds

18 2.4 millenia† 92 seconds

Lesson. Performance matters!

Note. Internet commerce is still secure: it depends on the difficulty of factoring 200-digit integers.

experts are still trying to develop

better algorithms for this problem

† estimated, using analytic number theory

20

Debugging your program: summary

Program development is a four-step process, with feedback.

EDIT your program.

COMPILE your program to create an executable file.

syntax error

TEST your program on realistic and real input data.

performance error

SUBMIT your program for independent testing and approval.

Telling a computer what to do when you know what you're doing

RUN your program to test that it works as you imagined.

semantic error

runtime error

21

COMPUTER SCIENCES E D G E W I C K / W A Y N E

PARTI : P RO G RA M M I N G I N JAVA

ht tp : / / introcs.cs.pr inceton.edu

R O B E R T S E D G E W I C K

KEVIN W A YNE

ComputerScience

An Interdisciplinary Approach

2. Conditionals & Loops

1.3

R O B E R T S E D G E W I C K

KEVIN W A YNE

ComputerScience

An Interdisciplinary Approach

3. Arrays

3. Arrays

• Basic concepts

• Typical array-processing code

• Two-dimensional arrays

Basic building blocks for programming

any program you might want to write

objects

functions and modules

arrays

conditionals and loops

Math text I/O

assignment statementsprimitive data types

graphics, sound, and image I/O

Ability to store and processhuge amounts of data

arrays

3

Your first data structure

Main purpose. Facilitate storage and manipulation of data.

Examples.

•52 playing cards in adeck.

•100 thousand students in an online class.

•1 billion pixels in a digital image.

•4 billion nucleotides in a DNA strand.

•73 billion Google queries per year.

•86 billion neurons in thebrain.

•50 trillion cells in the human body.

•6.02 × 102 3 particles in a mole.

A data structure is an arrangement of data that enables efficient processing by a program.

index value

0 2♥

1 6♠

2 A♦

3 A♥

...

49 3♣

50 K♣

51 4♠

An array is an indexed sequence of values of the same type.

4

Processing many values of the same type

double a0 = 0.0;

double a1 = 0.0;

double a2 = 0.0;

double a3 = 0.0;

double a4 = 0.0;

double a5 = 0.0;

double a6 = 0.0;

double a7 = 0.0;

double a8 = 0.0;

double a9 = 0.0;

...

a4 = 3.0;

...

a8 = 8.0;

...

double x = a4 + a8;

10 values, without arrays

tedious and error-prone code

double[] a;

a = new double[10];

...

a[4] = 3.0;

...

a[8] = 8.0;

...

double x = a[4] + a[8];

10 values, with an array

an easy alternative

double[] a;

a = new double[1000000];

...

a[234567] = 3.0;

...

a[876543] = 8.0;

...

double x = a[234567] + a[876543];

1 million values, with an array

scales to handle huge amounts ofdata

5

Memory representation of an array

A computer's memory is also an indexed sequence of memory locations.

•Each primitive type value occupies a fixed number of locations.

•Array values are stored in contiguous locations.

An array is an indexed sequence of values of the same type.

a[0]

Critical concepts

• Indices start at 0.

•Given i, the operation of accessing the value a[i]is extremely efficient.

•The assignment b = amakes the names band arefer to the same array.

stay tuned for many details

it does not copy the array, as with primitive types (stay tuned for details)

a for simplicity in this lecture, think of a as the memory address of the first location

the actual implementation in Java is just slightly more complicated.

a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]

6

Java language support for arrays

operation typical code

Declare an array double[] a;

Create an array of a given length a = new double[1000];

Refer to an array entry by index a[i] = b[j] + c[k];

Refer to the length of an array a.length;

Basic support

operation typical code

Default initialization to 0 for numeric types a = new double[1000];

Declare, create and initialize in one statement double[] a = new double[1000];

Initialize to literal values double[] x = { 0.3, 0.6, 0.1 };

Initialization options

BUT cost of creating an

array is proportional to its length.

no need to use a loop like

for (int i = 0; i < 1000; i++)

a[i] = 0.0;

7

Copying an array

To copy an array, create a new array , then copy all the values.

a

0.3 0.6 0.99 0.01 0.5

b

0.3 0.6 0.99 0.01 0.5

double[] b = new double[a.length]; for

(int i = 0; i < a.length; i++)

b[i] = a[i];

i i

Important note: The code b = adoes not copy an array (it makes band arefer to the same array).

a

0.3 0.6 0.99 0.01 0.5

b

double[] b = new double[a.length]; b

= a;

8

Programming with arrays: typical examples

double[] a = new double[N];

for (int i = 0; i < N; i++) a[i]

= Math.random();

Create an array with N random values

for (int i = 0; i < N; i++)

System.out.println(a[i]);

Print array values, one per line

double sum = 0.0;

for (int i = 0; i < N; i++) sum

+= a[i];

double average = sum / N;

Compute the average of array values

double max = a[0];

for (int i = 1; i < N; i++)

if (a[i] > max) max = a[i];

Find the maximum of array values

double[] b = new double[N];

for (int i = 0; i < N; i++)

b[i] = a[i];

For brevity, Nis a.lengthand b.length in all this code.

Copy to another array

int stake = Integer.parseInt(args[0]); int

goal = Integer.parseInt(args[1]); int trials =

Integer.parseInt(args[2]);

9

Access command-line args in system array

Pop quiz 1 on arrays

10

Q. What does the following code print?

public class PQarray1

{

public static void main(String[] args)

{

int[] a = new int[6];

int[] b = new int[a.length];

b = a;for (int i = 1; i < b.length; i++) b[i] =

i;

for (int i = 0; i < a.length; i++)

System.out.print(a[i] + " ");

System.out.println();

for (int i = 0; i < b.length; i++)

System.out.print(b[i] + " ");

System.out.println();

}

}

Pop quiz 1 on arrays

Q. What does the following code print?

public class PQarray1

{

public static void main(String[] args)

{

int[] a = new int[6];

int[] b = new int[a.length];

b = a;for (int i = 1; i < b.length; i++) b[i] =

i;

for (int i = 0; i < a.length; i++)

System.out.print(a[i] + " ");

System.out.println();

for (int i = 0; i < b.length; i++)

System.out.print(b[i] + " ");

System.out.println();

}

A. % java PQ4_1

0 1 2 3 4 5

After this, b and a refer to the same array

0 1 2 3 4 5}

11

Programming with arrays: typical bugs

a = new double[10];

for (int i = 0; i < 10; i++) a[i]

= Math.random();

Undeclared variable

double[] a;

for (int i = 0; i < 9; i++) a[i]

= Math.random();

Never created the array

Uninitialized array

double[] a = new double[10]; for

(int i = 1; i <= 10; i++)

a[i] = Math.random();

No a[10] (and a[0]unused)

Array index out of bounds

What type of data does a refer to?

12

Image sources

http://commons.wikimedia.org/wiki/File:CERN_Server_03.jpg

3. Arrays

• Basic concepts

• Examples of array-processing code

• Two-dimensional arrays

Example of array use: create a deck of cards

Define three arrays

•Ranks.

•Suits.

•Full deck.

Use nested forloops to put all the cards in the deck.

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 ...

2♣ 3♣ 4♣ 5♣ 6♣ 7♣ 8♣ 9♣ 10♣ J♣ Q♣ K♣ A♣ 2♦ 3♦ 4♦ 5♦ 6♦ 7♦ 8♦ 9♦ ...

String[] deck = new String[52];

deck

String[] suit = { "♣", "♦", "♥", "♠" };

0 1 2 3

♣ ♦ ♥ ♠suit

String[] rank = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A" };

0 1 2 3 4 5 6 7 8 9 10 11 12

2 3 4 5 6 7 8 9 10 J Q K A

for (int j = 0; j < 4; j++)

for (int i = 0; i < 13; i++)

deck[i + 13 j] = rank[i] + suit[j];

j

i

rank

better style to use rank.length and suit.lengthclearer in lecture to use 4 and 13

15

Example of array use: create a deck of cards

public class Deck

{

public static void main(String[] args)

{

String[] rank = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A" };

String[] suit = { "♣", "♦", "♥", "♠" };

String[] deck = new String[52]; for

(int j = 0; j < 4; j++)

for (int i = 0; i < 13; i++)

deck[i + 13 j] = rank[i] + suit[j];

for (int i = 0; i < 52; i++)

System.out.print(deck[i] + " ");

System.out.println();

}

}% java Deck

2♣ 3♣ 4♣ 5♣ 6♣ 7♣ 8♣ 9♣ 10♣ J♣ Q♣ K♣ A♣2♦ 3♦ 4♦ 5♦ 6♦ 7♦ 8♦ 9♦ 10♦ J♦ Q♦ K♦ A♦2♥ 3♥ 4♥ 5♥ 6♥ 7♥ 8♥ 9♥ 10♥ J♥ Q♥ K♥ A♥2♠ 3♠ 4♠ 5♠ 6♠ 7♠ 8♠ 9♠ 10♠ J♠ Q♠ K♠ A♠

%

no color in Unicode;

artistic license for lecture

16

Pop quiz 2 on arrays

Q. What happens if the order of the forloops in Deckis switched?

for (int j = 0; j < 4; j++)

for (int i = 0; i < 13; i++)

deck[i + 13 j] = rank[i] + suit[j];

for (int i = 0; i < 13; i++) for (int

j = 0; j < 4; j++)

deck[i + 13 j] = rank[i] + suit[j];

17

Pop quiz 2 on arrays

Q. What happens if the order of the forloops in Deckis switched?

for (int j = 0; j < 4; j++)

for (int i = 0; i < 13; i++)

deck[i + 13 j] = rank[i] + suit[j];

for (int i = 0; i < 13; i++) for (int

j = 0; j < 4; j++)

deck[i + 13 j] = rank[i] + suit[j];

A. The array is filled in a different order, but the output is the same.

18

j

0 1 2 3

♣ ♦ ♥ ♠suit

0 1 2 3 4 5 6 7 8 9 10 11 12

2 3 4 5 6 7 8 9 10 J Q K A

i

rank

deck

NOTE: Error on page 92 in 3rd printing of text (see errata list on booksite).

0 1 2 ... 12 13 14 15 ... 25 26 27 28 ... 38 39 40 41 ... 51

2♣ 3♣ 4♣ ... A♣ 2♦ 3♦ 4♦ ... A♦ 2♥ 3♥ 4♥ ... A♥ 2♠ 3♠ 4♠ ... A♠

Pop quiz 3 on arrays

Q. Change Deckto put the cards in rank order in the array.

% java Deck

2♣ 2♦ 2♥ 2♠ 3♣ 3♦ 3♥ 3♠ 4♣ 4♦ 4♥ 4♠ 5♣ 5♦ 5♥ 5♠ 6♣ 6♦ 6♥ 6♠ 7♣ 7♦ 7♥ 7♠ 8♣ 8♦ 8♥ 8♠ 9♣ 9♦ 9♥ 9♠

10♣ 10♦ 10♥ 10♠ J♣ J♦ J♥ J♠ Q♣ Q♦ Q♥ Q♠ K♣ K♦ K♥ K♠ A♣ A♦ A♥ A♠%

19

Pop quiz 3 on arrays

Q. Change Deckto put the cards in rank order in the array.

for (int i = 0; i < 13; i++) for (int

j = 0; j < 4; j++)

deck[4 i + j] = rank[i] + suit[j];

A.

% java Deck

2♣ 2♦ 2♥ 2♠ 3♣ 3♦ 3♥ 3♠ 4♣ 4♦ 4♥ 4♠ 5♣ 5♦ 5♥ 5♠ 6♣ 6♦ 6♥ 6♠ 7♣ 7♦ 7♥ 7♠ 8♣ 8♦ 8♥ 8♠ 9♣ 9♦ 9♥ 9♠

10♣ 10♦ 10♥ 10♠ J♣ J♦ J♥ J♠ Q♣ Q♦ Q♥ Q♠ K♣ K♦ K♥ K♠ A♣ A♦ A♥ A♠%

20

0 1 2 3 4 5 6 7 8 9 10 11 12 ...

2♣ 2♦ 2♥ 2♠ 3♣ 3♦ 3♥ 3♠ 4♣ 4♦ 4♥ 4♠ 5♣ ...

0 1 2 3

♣ ♦ ♥ ♠suit

0 1 2 3 4 5 6 7 8 9 10 11 12

2 3 4 5 6 7 8 9 10 J Q K A

i

rank

j

deck

21

Array application: take a card, any card

Problem: Print a random sequence of N cards.

52);

for (int i = 0; i < N; i++)

{int r = (int) (Math.random()

System.out.println(deck[r]);

}

Algorithm

Take N from the command line and do the following N times

•Calculate a random index r between 0 and 51.

•Print deck[r].

Implementation: Add this code instead of printing deckin Deck.

Note: Same method is effective for printing a random sequence from any data collection.

each value between 0 and 51 equally likely

22

Array application: random sequence of cards

public class DrawCards{

public static void main(String[] args){

int N = Integer.parseInt(args[0]);

String[] rank = {"2", "3", "4", "5", "6", "7", "8", "9","10", "J", "Q", "K", "A" };

String[] suit = { "♣", "♦", "♥", "♠" };

String[] deck = new String[52];for (int i = 0; i < 13; i++) for (int

j = 0; j < 4; j++)

deck[i + 13 j] = rank[i] + suit[j];

for (int i = 0; i < N; i++)

{

int r = (int) (Math.random() 52);

System.out.print(deck[r] + " ");

}

System.out.println();

}}

% java DrawCards 10

6♥ K♦ 10♠ 8♦ 9♦ 9♥ 6♦ 10♠ 3♣ 5♦

% java DrawCards 10

2♦ A♠ 5♣ A♣ 10♣ Q♦ K♣ K♠ A♣ A♦

% java DrawCards 10

6♠ 10♦ 4♥ A♣ K♥ Q♠ K♠ 7♣ 5♦ Q♠

% java DrawCards 10

A♣ J♣ 5♥ K♥ Q♣ 5♥ 9♦ 9♣ 6♠ K♥

Note: Sample is with replacement (same card can appear multiple times). appears twice23

Array application: shuffle and deal from a deck of cards

Problem: Print N random cards from a deck.

Algorithm: Shuffle the deck, then deal.

•Consider each card index i from 0 to 51.

•Calculate a random index r between i and 51.

•Exchange deck[i]with deck[r]

• Print the first N cards in the deck.

(52-i));

for (int i = 0; i < 52; i++)

{int r = i + (int) (Math.random()

String t = deck[r];

deck[r] = deck[i];

deck[i] = t;

}for (int i = 0; i < N; i++)

System.out.print(deck[i]);

System.out.println();

Implementationeach value

between i and 51 equally likely

24

Array application: shuffle a deck of 10 cards (trace)

(10-i));

25

for (int i = 0; i < 10; i++)

{int r = i + (int) (Math.random()

String t = deck[r];

deck[r] = deck[i];

deck[i] = t;

}

i rdeck

0 1 2 3 4 5 6 7 8 9

2♣ 3♣ 4♣ 5♣ 6♣ 7♣ 8♣ 9♣ 10♣ J♣

0 7 9♣ 3♣ 4♣ 5♣ 6♣ 7♣ 8♣ 2♣ 10♣ J♣

1 3 9♣ 5♣ 4♣ 3♣ 6♣ 7♣ 8♣ 2♣ 10♣ J♣

2 9 9♣ 5♣ J♣ 3♣ 6♣ 7♣ 8♣ 2♣ 10♣ 4♣

3 9 9♣ 5♣ J♣ 4♣ 6♣ 7♣ 8♣ 2♣ 10♣ 3♣

4 6 9♣ 5♣ J♣ 4♣ 8♣ 7♣ 6♣ 2♣ 10♣ 3♣

5 9 9♣ 5♣ J♣ 4♣ 8♣ 3♣ 6♣ 2♣ 10♣ 7♣

6 8 9♣ 5♣ J♣ 4♣ 8♣ 3♣ 10♣ 2♣ 6♣ 7♣

7 9 9♣ 5♣ J♣ 4♣ 8♣ 3♣ 10♣ 7♣ 6♣ 2♣

8 8 9♣ 5♣ J♣ 4♣ 8♣ 3♣ 10♣ 7♣ 6♣ 2♣

9 9 9♣ 5♣ J♣ 4♣ 8♣ 3♣ 10♣ 7♣ 6♣ 2♣

Q. Why does this method work?

• Uses only exchanges, so the deck after

the shuffle has the same cards as before.

• N −i equally likely values for deck[i].

• Therefore N ×(N −1)×(N −1)... ×2×1 = N !

equally likely values for deck[].

Initial order is immaterial.

Note: Same method is effective for randomly rearranging any type of data.

Array application: shuffle and deal from a deck of cards

public class DealCards{

public static void main(String[] args){

int N = Integer.parseInt(args[0]);

String[] rank = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A" };

String[] suit = { "♣", "♦", "♥", "♠" };

String[] deck = new String[52]; for (int i = 0; i < 13; i++)

for (int j = 0; j < 4; j++)deck[i + 13 j] = rank[i] + suit[j];

(52-i));

for (int i = 0; i < 52; i++){

int r = i + (int) (Math.random() String t = deck[r];deck[r] = deck[i]; deck[i] = t;

}

for (int i = 0; i < N; i++)

System.out.print(deck[i]);

System.out.println();

}}

% java DealCards 5

9♣ Q♥ 6♥ 4♦ 2♠

random poker hand

% java DealCards 13

3♠ 4♥ 10♦ 6♥ 6♦ 2♠ 9♣ 8♠ A♠ 3♥ 9♠ 5♠ Q♥

random bridge hand

26

Coupon collector

27

9♣ 5♠ 8♥ 10♦ 2♠ A♠ 10♥ Q♦ 3♠ 9♥ 5♦ 9♣ 7♦ 2♦ 8♣ 6♣ Q♥ K♣ 10♥ A♦ 4♦ J♥

Example: Collect all ranks in a random sequence of cards (M =

Collection

2 3 4 5 6 7 8 9 10 J Q K A

2♠ 3♠ 4♦ 5♠ 6♣ 7♦ 8♥ 9♣ 10♦ J♥ Q♦ K♣ A♠

2♦ 5♦ 8♣ 9♥

9♣

10♥

10♥

Q♥ A♦

Sequence

22 cards needed

to complete

collection

Coupon collector problem

•M different types of coupons.

•Collector acquires random coupons, one at a time, each type equally likely.

Q. What is the expected number of coupons needed to acquire a full collection?

Array application: coupon collector

public class Coupon{

public static void main(String[] args){

int M = Integer.parseInt(args[0]);int cards = 0; // number of cards collected int distinct = 0; // number of distinct cards

boolean[] found = new boolean[M]; while (distinct < M){

int r = (int) (Math.random() M); cards++;if (!found[r])

{distinct++; found[r] = true;

}}

System.out.println(cards);}

}

Key to the implementation

•Create a boolean array of length M.

(Initially all falseby default.)

•When r generated, check the r th

value in the array.

• If true, ignore it (not new).

• If false, count it as new distinct

value (and set r th entry to true)

% java Coupon 13

46

% java Coupon 13

22

28

% java Coupon 13

54

% java Coupon 13

27

Coupon collector simulation

•Generate random intvalues

between 0 and M −1.

•Count number used to generate

each value at least once.

Array application: coupon collector (trace for M = 6)

boolean[] found = new boolean[M];

while (distinct < M)

{

int r = (int) (Math.random() M);

cards++;

if (!found[r])

{distinct++;

found[r] = true;

}

}

29

rfound

distinct cards0 1 2 3 4 5

F F F F F F 0 0

2 F F T F F F 1 1

0 T F T F F F 2 2

4 T F T F T F 3 3

0 T F T F T F 3 4

1 T T T F T F 4 5

2 T T T F T F 4 6

5 T T T F T T 5 7

0 T T T F T T 5 8

1 T T T F T T 5 9

3 T T T T T T 6 10

Simulation, randomness, and analysis (revisited)

Pierre-Simon Laplace

1749-1827

Coupon collector problem

•M different types of coupons.

•Collector acquires random coupons, one at a time, each type equally likely.

Q. What is the expected number of coupons needed to acquire a full collection?

% java Coupon 4

11

% java Coupon 13

38

% java Coupon 1200

8789

% java Coupon 12534

125671

type M expected wait

playing card suits 4 8

playing card ranks 13 41

baseball cards 1200 9201

Magic™ cards 12534 125508

Remarks

•Computer simulation can help validate mathematical analysis.

•Computer simulation can also validate software behavior.Example: Is Math.random()

simulating randomness?

A. (known via mathematical analysis for centuries) About M ln M + .57721M .

30

Simulation, randomness, and analysis (revisited)

public class Gambler{

public static void main(String[] args){

int stake = Integer.parseInt(args[0]); int goal= Integer.parseInt(args[1]); int trials =Integer.parseInt(args[2]);

int wins = 0;for (int i = 0; i < trials; i++){

int t = stake;while (t > 0 && t < goal){

if (Math.random() < 0.5) t++; else t--;

}if (t == goal) wins++;

}System.out.println(wins + " wins of " + trials);

}}

Gambler's ruin simulation, previous lecturepublic class CouponCollector{

public static void main(String[] args){

int M = Integer.parseInt(args[0]);int trials = Integer.parseInt(args[1]); int cards = 0;boolean[] found;

for (int i = 0; i < trials; i++){

int distinct = 0;found = new boolean[M]; while (distinct < M){

int r = (int) (Math.random() M); cards++;if (!found[r]){

distinct++; found[r] = true;

}}

}System.out.println(cards/trials);

}}

31

Analogous code for coupon collector, this lecture

Once simulation is debugged, experimental evidence is easy to obtain.

Simulation, randomness, and analysis (revisited)

41

% java

8CouponCollector 4 1000000

% java CouponCollector 13 1000000

% java

236CouponCollector 52 100000

% java

9176CouponCollector 1200 10000

% java

12592

0

CouponCollector 12534 1000

Predicted by mathematical analysis

type M M ln M + .57721M

playing card suits 4 8

playing card ranks 13 41

playing cards 52 236

baseball cards 1200 9201

magic cards 12534 125508

Observed by computer simulation

Hypothesis. Centuries-old analysis is correct and Math.random()simulates randomness.32

Coupon collector problem

•M different types of coupons.

•Collector acquires random coupons, one at a time, each type equally likely.

Q. What is the expected number of coupons needed to acquire a full collection?

Image sources

http://www.vis.gr.jp/~nazoya/cgi-bin/catalog/img/CARDSBIC809_red.jpg

http://www.alegriphotos.com/Shuffling_cards_in_casino-photo-deae1081e5ebc6631d6871f8b320b808.html

http://iveypoker.com/wp-content/uploads/2013/09/Dealing.jpg http://upload.wikimedia.org/wikipedia/commons/b/bf/Pierre-

Simon,_marquis_de_Laplace_(1745-1827)_-_Guérin.jpg

3. Arrays

• Basic concepts

• Examples of array-processing code

• Two-dimensional arrays

35

Two-dimensional arrays

Main purpose. Facilitate storage and manipulation of data.

Examples

•Matrices in math calculations.

•Grades for students in an online class.

•Outcomes of scientific experiments.

•Transactions for bank customers.

•Pixels in a digital image.

•Geographic data

• ...

0 1 2 3 4 5 ...

0 A A C B A C

1 B B B B A A

2 C D D B C A

3 A A A A A A

4 C C B C B B

5 A A A B A A

...

grade

stu

dent

ID

x-coordinate

y-c

oord

inate

A two-dimensional array is a doubly-indexed sequence of values of the same type.

Java language support for two-dimensional arrays (basic support)

operation typical code

Declare a two-dimensional array double[][] a;

Create a two-dimensional array of a given length a = new double[1000][1000];

Refer to an array entry by index a[i][j] = b[i][j] c[j][k];

Refer to the number of rows a.length;

Refer to the number of columns a[i].length;

Refer to row i a[i]

can be different

for each row

a[][]

a[1]

a[0][0] a[0][1] a[0][2] a[0][3] a[0][4] a[0][5] a[0][6] a[0][7] a[0][8] a[0][9]

a[1][0] a[1][1] a[1][2] a[1][3] a[1][4] a[1][5] a[1][6] a[1][7] a[1][8] a[1][9]

a[2][0] a[2][1] a[2][2] a[2][3] a[2][4] a[2][5] a[2][6] a[2][7] a[2][8] a[2][9]

no way to refer to column j

a 3-by-10 array

36

Java language support for two-dimensional arrays (initialization)

operation typical code

Default initialization to 0

for numeric types a = new double[1000][1000];

Declare, create and initialize

in a single statement double[][] a = new double[1000][1000];

Initialize to literal values

double[][]

{

p =

{ .92, .02, .02, .02, .02 },

{ .02, .92, .32, .32, .32 },

{ .02, .02, .02, .92, .02 },

{ .92, .02, .02, .02, .02 },

{ .47, .02, .47, .02, .02 },

};

BUT cost of creating an

array is proportional to its size.

no need to use nested loops like

for (int i = 0; i < 1000; i++) for (int j

= 0; j < 1000; j++)

a[i][j] = 0.0;

37

Application of arrays: vector and matrix calculations

Mathematical abstraction: matrix

Java implementation: 2D array

Vector addition

double[] c = new double[N];

for (int i = 0; i < N; i++)

c[i] = a[i] + b[i];

Matrix addition

double[][] c = new double[N][N]; for

(int i = 0; i < N; i++)

for (int j = 0; j < N; j++) c[i][j] =

a[i][j] + b[i][j];

38

.70 .20 .10

.30 .60 .10

.50 .10 .40

.80 .30 .50

.10 .40 .10

.10 .30 .40

1.5 .50 .60

.40 1.0 .20

.60 .40 .80

+ =.30 .60 .10 + =.50 .10 .40 .80 .70 .50

Mathematical abstraction: vector

Java implementation: 1D array

Application of arrays: vector and matrix calculations

Mathematical abstraction: matrix

Java implementation: 2D array

* =

.70 .20 .10

.30 .60 .10

.50 .10 .40

.80 .30 .50

.10 .40 .10

.10 .30 .40

.59 .32 .41

.31 .36 .25

.45 .31 .42

.30 .60 .10 .25· =.50 .10 .40

Vector dot product

double sum = 0.0;

for (int i = 0; i < N; i++) sum

+= a[i] b[i];

Matrix multiplication

double[][] c = new double[N][N]; for

(int i = 0; i < N; i++)

for (int j = 0; j < N; j++) for (int

k = 0; k < N; k++)

c[i][j] += a[i][k] b[k][j];

i x[i] y[i] x[i] y[i] sum

0 0.3 0.5 0.15 0.15

1 0.6 0.1 0.06 0.21

2 0.1 0.4 0.04 0.25

end-of-loop trace

39

Mathematical abstraction: vector

Java implementation: 1D array

Pop quiz 4 on arrays

Q. How many multiplications to multiply two N-by-N matrices?

1. N

2. N 2

3. N 3

4. N 4

double[][] c = new double[N][N]; for

(int i = 0; i < N; i++)

for (int j = 0; j < N; j++) for (int

k = 0; k < N; k++)

c[i][j] += a[i][k] b[k][j];

40

1. N

2. N 2

3. N 3

4. N 4

Pop quiz 4 on arrays

Q. How many multiplications to multiply two N-by-N matrices?

double[][] c = new double[N][N]; for

(int i = 0; i < N; i++)

for (int j = 0; j < N; j++) for (int

k = 0; k < N; k++)

c[i][j] += a[i][k] b[k][j];

Nested forloops: N × N × N

41

Approach: Use Monte Carlo simulation, recording visited positions in an N-by-N array.

Q. What are the chances of reaching a dead end? dead end

escapeModel: a random process in an N-by-N lattice

•Start in the middle.

•Move to a random neighboring intersection

but do not revisit any intersection.

•Outcome 1 (escape): reach edge of lattice.

•Outcome 2 (dead end): no unvisited neighbors.

Self-avoiding random walks

A dog walks around at

random in a city, never

revisiting any intersection.

Q. Does the dog escape?

42

Self-avoiding random walks

43

Application of 2D arrays: self-avoiding random walks

public class SelfAvoidingWalker{

public static void main(String[] args){

int N = Integer.parseInt(args[0]);int trials = Integer.parseInt(args[1]); int deadEnds = 0;for (int t = 0; t < trials; t++){

boolean[][] a = new boolean[N][N]; int x = N/2, y = N/2;

while (x > 0 && x < N-1 && y > 0 && y < N-1){

if (a[x-1][y] && a[x+1][y] && a[x][y-1] && a[x][y+1]){ deadEnds++; break; }

a[x][y] = true;double r = Math.random();if (r < 0.25) { if (!a[x+1][y]) x++; }else if (r < 0.50) { if (!a[x-1][y]) x--; }else if (r < 0.75) { if (!a[x][y+1]) y++; }else if (r < 1.00) { if (!a[x][y-1]) y--; }

}}System.out.println(100 deadEnds/trials + "% dead ends");

}}

% java SelfAvoidingWalker 5% dead ends

10 100000

% java SelfAvoidingWalker 32% dead ends

20 100000

% java SelfAvoidingWalker 58% dead ends

30 100000

% java SelfAvoidingWalker 77% dead ends

40 100000

% java SelfAvoidingWalker 87% dead ends

50 100000

% java SelfAvoidingWalker 93% dead ends

60 100000

% java SelfAvoidingWalker 96% dead ends

70 100000

% java SelfAvoidingWalker 98% dead ends

80 100000

% java SelfAvoidingWalker 99% dead ends

90 100000

% java SelfAvoidingWalker 100 10000099% dead ends

0%

25%

50%

75%

100%

10 20 30 40 50 60 70 80 90 100

44

Simulation, randomness, and analysis (revisited again)

Remark: Computer simulation is often the only effective way to study a scientific phenomenon.

Self-avoiding walk in an N-by-N lattice

•Start in the middle.

•Move to a random neighboring intersection (do not revisit any intersection).

A. 99+% for N >100 (clear from simulations). YOU can!

Applications

•Model the behavior of solvents and polymers.

•Model the physics of magnetic materials.

• (many other physical phenomena)

Computational models play

an essential role in modern

scientific research.

Paul Flory

1910-1985Nobel Prize 1974Q. What is the probability of reaching a dead end?

A. Nobody knows (despite decades of study).Mathematicians and physics researchers cannot solve the problem.

45

Your first data structure

Some applications in this course:

LFSR

^

digital audio

digital images

Arrays: A basic building block in programming

•They enable storage of large amounts of data (values all of the same type).

•With an index, a program can instantly access a given value.

•Efficiency derives from low-level computer hardware organization (stay tuned).

N-body simulation

46

Image sources

http://en.wikipedia.org/wiki/Airedale_Terrier#mediaviewer/File:Airedale_Terrier.jpg

http://www.nobelprize.org/nobel_prizes/chemistry/laureates/1974/flory_postcard.jpg