Introduction to Java Programming
Introduction to Java Programming
Basic Programming
Computer
Science An Interdisciplinary Approach
Concepts
R O B ER T S ED G EW IC K
1.1–1.2 KEVIN W A YNE
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.
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)
Programming
• Is not just for experts.
• Is a natural, satisfying and creative experience.
• Enables accomplishments not otherwise possible.
• The path to a new world of intellectual endeavor.
Challenges
• Need to learn what computers can do.
• Need to learn a programming language. Telling a computer what to do
− Don Knuth
4
Telling a computer what to do
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
millions of developers
Java economy billions of devices
• Mars rover.
• Cell phones.
• Blu-ray Disc.
• Web servers.
• Medical devices.
• Supercomputing.
•…
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 “ There are only two kinds of
• N o language is perfect. programming languages: those
• You need to start with some language. people always [gripe] about and
those nobody uses.”
Your programs will primarily consist of these plus identifiers (names) that you make up.
8
Anatomy of your first program
program name
main()method
text file named
[Link] public class HelloWorld
{
public static void main(String[] args)
{
[Link]("Hello, World");
}
}
body of main()
(a single statement)
9
Anatomy of your next several programs
program name
main()method
text file named
[Link] public class MyProgram
{
public static void main(String[] args)
{
...
}
}
body of main()
(a sequence of statements)
10
Pop quiz on "your first program"
% javac [Link]
% java MyProgram
Main method not public.
% javac [Link]
[Link][Link] invalid method declaration; return type required public
static main(String[] args)
^
11
Pop quiz on "your first program"
% javac [Link]
% java MyProgram
Main method not public.
% javac [Link]
[Link][Link] invalid method declaration; return type required public
static main(String[] args)
^
A. Check HelloWorld. Aha! Forgot “void”. public static void main(String[] args)
12
Three versions of the same program.
/*************************************************************************
* Compilation: javac [Link]
* 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) { [Link]("Hello, World"); } }
Lesson: Fonts, color, comments, and extra space are not relevant in Java
language. 14
Note on program style
Different styles are appropriate in different contexts.
• Integrated development environment
• Booksite
• Book
• Your code 6 Elements of Prog ramming
• Stifle creativity.
{
[Link]("Hello, World");
[Link]();
}
}
• Confuse style with language. 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).
% javac [Link]
• Make it easier to spot errors. 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 [Link] (by convention in
Java). The program’s sole action is to print a message back to the terminal win-
Bottom line for you: Listen to the person assigning your grade.
or your boss! 15
Image sources
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
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
17
Software for program development
EDIT
COMPOSE
COMPILE RUN
REHEARSE PLAY
A significant difference with programs: We can use our computers to facilitate the process.
Program development environment: Software for editing, compiling and running programs.
2000
19
Program development with switches and lights
Circa 1970: Use switches to input binary program code and data, lights to read output.
switches
Mid 1970s: Use punched cards to input program code and data, line printer for output.
Late 1970s: Use terminal for editing program, reading output, and controlling computer.
VT-100 terminal
virtual TV set
23
Program development with personal computers (another approach)
“Integrated Development
Environment” (IDE)
“run” button
[Link]
“compile” button
pseudo-command line
24
Software for program development: tradeoffs
Pros Pros
• Approach works with any language. • Easy-to-use language-specific tools.
• Useful beyond programming. • System-independent (in principle).
• Used by professionals. • Used by professionals.
• Has withstood the test of time. • Can be helpful to beginners.
Cons Cons
• Good enough for long programs? • Overkill for short programs?
• Dealing with independent applications. • Big application to learn and maintain.
• Working at too low a level? • Often language- or system-specific.
Two approaches that have served for decades and are still
effective:
• multiple virtual terminals.
Macbook Air 2 0 1 4
Apple Macintosh 1 9 8 4
IBM PC 1 9 9 0 s
Wintel ultrabooks 2 0 1 0 s
Xerox Alto 1 9 7 8
26
Image sources
[Link]
File:Koji_Uehara_2_on_June_15,_2013.jpg
[Link]
[Link]
1. Basic Programming Concepts
• Why programming?
• Program development
• Built-in data types
• Type conversion
Built-in data types
'A'
char characters compare
'@'
"Hello World"
String sequences of characters concatenate
"CS is fun"
17
int integers add, subtract, multiply, divide
12345
3.1415
double floating-point numbers add, subtract, multiply, divide
6.022e23
true
boolean truth values and, or, not
false
30
Pop quiz on data types
31
Basic Definitions
variables
int a;
declaration statements
int b;
assignment statements
a = 1234;
b = 99;
int c = a + b;
combined declaration
and assignment statement
literals
32
Variables, literals, declarations, and assignments example: exchange values
A. N o way for us to confirm that it does the exchange! (Need output, stay tuned).
33
Data type for computing with strings: String
Stringdata type
typical literals "Hello, " "1 " " " Important note:
operator +
character
"1234" + " + " + "99" "1234 + 99" Ex 2: spaces "1234" + " + " + "99"
"1234" + "99" "123499"
space
characters
34
Example of computing with strings: subdivisions of a ruler
35
Input and output
is necessary for us to provide data to our programs and to learn the result of computations.
command-line
Humans prefer to work with strings. arguments
Output
standard output
• [Link]() method prints the given string.
• Java automatically converts numbers to strings for output. Bird's eye view of a Java program
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 [Link]() to convert the strings to integers.
Stay tuned for many more options for input and output, and more details on type conversion.
36
Input and output warmup: exchange values
A. Reads two integers from the command line, then prints them out in the opposite order.
38
Data type for computing with integers: int
intdata type
operator + − / %
not quite the same as integers
Examples of intoperations
39
Data type for computing with floating point numbers: double
doubledata type
[Link](2.0) 1.4142135623730951
"not a number"
floatdata type
short
int, float
long, double
41
Excerpts from Java’s Math Library
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.
45
Example of computing with booleans: leap year test
46
Image sources
[Link]
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.
The Java compiler is your friend : it checks for type errors in your code.
% javac [Link]
[Link][Link] operator cannot be applied to [Link],int String
s = "123" 2;
^
1 error
When appropriate, we often convert a value from one type to another to make types match.
49
Type conversion with built-in types
11 0.25
String
double
"x: 99"
2.75
• Make numeric types match if no loss of precision.
Cast for values that belong to multiple types. (int) 2.71828 int 2
• Ex: small integers can be short, intor long. (int) [Link](2.71828) int 3
a. (7/2) 2.0
b. ( 7 / 2.0 ) 2
c. "2" + 2
d. 2.0 + "2"
51
Pop quiz on type conversion
52
An instructive story about type conversion
54
Summary
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 if statement
• Loops: the while statement
• An alternative: the for loop
• Nesting
• Debugging
Context: basic building blocks for programming
objects
arrays
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.
true boolean 1
statement 1
false
statement 2 statement 1
false
statement 4
statement 3
% java Flip
Tails
% java Flip
Heads
6
Example of if statementuse: 2-sort
A. Reads two integers from the command line, then prints them out in numerical order.
7
Pop quiz on if statements
8
Pop quiz on if statements
}
}
9
Example of if statement use: error checks
Good programming practice. Use conditionals to check for and avoid runtime errors.
10
Image sources
[Link]
[Link]
[Link] [[Link]]
Computer 2. Conditionals and loops
Science
An Interdisciplinary Approach
R O B ER T S ED G EW IC K
KEVIN W A YNE
2. Conditionals & Loops
• Conditionals: the if statement
• Loops: the while statement
• An alternative: the for loop
• Nesting
• Debugging
The while loop
i <= n ? false
Example:
int i = 0;
int v = 1; true
while (i <= n)
[Link](v);
{
[Link](v); i
= i + 1; i = i + 1;
v= 2 v;
} v=2 v;
{ 0 1 true
public static void main(String[] args)
1 2 true
{
int n = [Link](args[0]); int i 2 4 true
= 0;
3 8 true
int v = 1; while
4 16 true
(i <= n)
{ 5 32 true
[Link](v); i
6 64 true
= i + 1; % java PowersOfTwo 6
7 128 false 1
v= 2 v;
2
} 4
} 8
16
}
32
64
5
Pop quiz on while loops
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
7
Example of while loop use: implement [Link]()
8
Newton-Raphson method
root: f (x) = 0
9
Image sources
[Link]
[Link]
[Link]
2. Conditionals & Loops
• Conditionals: the if statement
• Loops: the while statement
• An alternative: the for loop
• Nesting
• Debugging
The for loop
An alternative repetition structure. Why? Can provide code that is more compact and understandable.
12
Examples of for loop use
sum i
int sum = 0; 1 1
for (int i = 1; i <= N; i++) sum
3 2
+= i; trace at end of loop for N = 4
6 3
[Link](sum);
10 4
Compute sum (1 + 2 + 3 + . . . + N)
product i
long product = 1; 1 1
for (int i = 1; i <= N; i++) 2 2
product = i; 6 3
[Link](product); 24 4
2nk
Compute N! = 1 * 2 * 3 * . . . * N k
U
0 0
1 1.57079632...
for (int k = 0; k <= N; k++) [Link](k + " "
2 3.14159265...
+ 2 [Link] k/N);
3 4.71238898...
Print a table of function values 4 6.28318530...
int v = 1; 2
while (v <= N/2) 4 trace at end of loop for N = 2 3
v = 2 v; 8
[Link](v); 16
15
Pop quiz on for loops
Beginning-of-loop trace
public class PQfor
{ A. i f g
public static void main(String[] args) 0 0 1
{
1 1 0
int f = 0, g = 1;
for (int i = 0; i <= 10; i++) 2 1 1
{ 3 2 1
[Link](f); f
4 3 2
= f + g;
5 5 3
g = f - g;
} 6 8 5
} 7 13 8
}
8 21 13
9 34 21
10 55 34
values printed
16
Computer 2. Conditionals and loops
Science
An Interdisciplinary Approach
R O B ER T S ED G EW IC K
KEVIN W A YNE
2. Conditionals & Loops
• Conditionals: the if statement
• Loops: the while statement
• 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.
Example:
for (int t = 0; t < trials; t++)
{
int cash = stake;
while (cash > 0 && cash < goal)
if-elsestatement
if ([Link]() < 0.5) cash++;
within a whileloop
else cash--; within a forloop
if (cash == goal) wins++;
}
$311,950 + 35%
4
Pop quiz on nested if statements
5
Pop quiz on nested if statements
6
Gambler's ruin problem
int wins = 0;
• Run all the experiments. for (int t = 0; t < trials; t++) forloop
{
int cash = stake; while loop
• Run one experiment. while (cash > 0 && cash < goal) within a for loop
{
if ([Link]() < 0.5) cash++; if statement
• Make one bet. else cash--; within a while loop
} within a for loop
• If goal met, count the win. if (t == goal) wins++;
}
• Print #wins and # trials. [Link](wins + " wins of " + trials);
}
}
% java Gambler 5 25 1000
191 wins of 1000
8
Digression: simulation and analysis
Facts (known via mathematical analysis for centuries) Early scientists were
fascinated by the study
• Probability of winning = stake ÷ goal. of games of chance.
• Expected number of bets = stake × desired gain.
Christiaan Huygens
1629- 1695
stake goal trials
Example
% java Gambler 5 25 1000
• 2 0 % chance of turning $ 5 0 0 into $2500. 500/2500 = 20%
191 wins of 1000
• Expect to make 1 million $ 1 bets. 500*(2500 - 500) = 1,000,000
% java Gambler 5 25 1000
203 wins of 1000
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.
9
Image sources
[Link]
[Link]
COMPUTER SCIENCE
S E D G E W IC K / W A Y N E
PA RTI : PRO G RA M M I N G I N JAVA
[Link] [Link] n g
Debugging
is 9 9 % of program development in any programming language, even for experts.
EDIT
COMPILE RUN
“ 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
Impossible ideal: "Please compile, execute, and debug m y program." Why is this impossible? Stay tuned.
Good news. Conditionals and loops provide structure that helps us understand our programs.
3,757,208 = 2 2 2 7 1 3 1 3 3 9 7
Problem: Factor a large integer n.
Application: Cryptography. 9 8 = 2 7 7
17 = 17
✓
% java Factors 98
2 7 7% 98 = 2 × 7× 7
16
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)
% java Factors 98 {
2 7 7% need newline % javac [Link] long n = [Link](args[0]); for
% java Factors 5 ( int i = 2; i < n; i++)
TRACE 2 5 {
% java Factors 5 TRACE 3 5 while (n % i == 0)
??? no output TRACE 4 5
{
% java Factors 6
2
[Link](i + " "); n =
% java Factors 6 TRACE 2 3 n / i;
2 ??? where’s the 3? }
[Link]("TRACE " + i + " " + n);
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)
??? {
%$%@$#!! % java Factors 5 long n = [Link](args[0]); for
forgot to recompile TRACE 2 5
( int i = 2; i < N; i++)
TRACE 3 5
TRACE 4 5 {
% javac [Link] while (n % i == 0)
% java Factors 5 {
5 [Link](i + " "); n =
% java Factors 6 n / i;
23
% java Factors 98
}
277 }
% java Factors 3757208 if (n > 1) [Link](n); else
2 2 2 7 13 13 397 [Link]();
}
Note: This working program
} still has a bug (stay tuned).
18
Debugging a program: performance
Note. Internet commerce is still secure: it depends on the difficulty of factoring 200-digit integers.
20
Debugging your program: summary
runtime error
COMPILE your program to create an executable file. Telling a computer what to do
when you k n ow what you're doing
semantic error
performance error
R O B ER T S ED G EW IC K
1.3 KEVIN W A YNE
http:// [Link]
Computer 3. Arrays
Science
An Interdisciplinary Approach
R O B ER T S ED G EW IC K
KEVIN W A YNE
3. Arrays
• Basic concepts
• Typical array-processing code
• Two-dimensional arrays
Basic building blocks for programming
objects
arrays
Ability to store and process
conditionals and loops huge amounts of data
3
Your first data structure
double a0 = 0.0;
double a1 = 0.0;
double a2 = 0.0; 10 values, with an array 1 million values, with an array
double a3 = 0.0;
double a4 = 0.0;
double[] a; double[] a;
double a5 = 0.0;
a = new double[10]; a = new double[1000000];
double a6 = 0.0;
... ...
double a7 = 0.0;
a[4] = 3.0; a[234567] = 3.0;
double a8 = 0.0;
... ...
double a9 = 0.0;
a[8] = 8.0; a[876543] = 8.0;
... ...
...
a4 = 3.0;
double x = a[4] + a[8]; double x = a[234567] + a[876543];
...
a8 = 8.0;
...
double x = a4 + a8; an easy alternative scales to handle huge amounts of data
5
Memory representation of an array
A computer's memory is also an indexed sequence of memory locations. stay tuned for many details
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
Critical concepts
• Indices start at 0.
• Given i, the operation of accessing the value a[i]is extremely efficient.
• The assignment b = a makes the names b and a refer to the same array. it does not copy the array,
as with primitive types
(stay tuned for details)
6
Java language support for arrays
Initialization options
no need to use a loop like
for (int i = 0; i < 1000; i++)
a[i] = 0.0;
operation typical code
To copy an array, create a new array , then copy all the values.
a i b i
0.3 0.6 0.99 0.01 0.5 0.3 0.6 0.99 0.01 0.5
Important note: The code b = adoes not copy an array (it makes band arefer to the same array).
a b
8
Programming with arrays: typical examples
Access command-line args in system array For brevity, Nis [Link] [Link] all this code.
int stake = [Link](args[0]); int
goal = [Link](args[1]); int trials = Copy to another array
[Link](args[2]); double[] b = new double[N];
for (int i = 0; i < N; i++)
b[i] = a[i];
Compute the average of array values Find the maximum of array values
double sum = 0.0; double max = a[0];
for (int i = 0; i < N; i++) sum
for (int i = 1; i < N; i++)
+= a[i]; if (a[i] > max) max = a[i];
double average = sum / N;
9
Pop quiz 1 on arrays
b = a;
for (int i = 1; i < [Link]; i++) b[i] =
i;
10
Pop quiz 1 on arrays
11
Programming with arrays: typical bugs
12
Image sources
[Link]
3. Arrays
• Basic concepts
• Examples of array-processing code
• Two-dimensional arrays
Example of array use: create a deck of cards
Define three arrays 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 13 14 15 16 17 18 19 20 ...
deck 2♣ 3♣ 4♣ 5♣ 6♣ 7♣ 8♣ 9♣ 10♣ J♣ Q♣ K♣ A♣ 2♦ 3♦ 4♦ 5♦ 6♦ 7♦ 8♦ 9♦ ...
15
Example of array use: create a deck of cards
16
Pop quiz 2 on arrays
for (int j = 0; j < 4; j++) for (int i = 0; i < 13; i++) for (int
for (int i = 0; i < 13; i++) j = 0; j < 4; j++)
deck[i + 13 j] = rank[i] + suit[j]; deck[i + 13 j] = rank[i] + suit[j];
17
Pop quiz 2 on arrays
for (int j = 0; j < 4; j++) for (int i = 0; i < 13; i++) for (int
for (int i = 0; i < 13; i++) j = 0; j < 4; j++)
deck[i + 13 j] = rank[i] + suit[j]; deck[i + 13 j] = rank[i] + suit[j];
A. The array is filled in a different order, but the output is the same. j
0 1 2 3
suit ♣ ♦ ♥ ♠
i
0 1 2 3 4 5 6 7 8 9 10 11 12
rank 2 3 4 5 6 7 8 9 10 J Q K A
NOTE: Error on page 9 2 in 3rd printing of text (see errata list on booksite).
18
Pop quiz 3 on arrays
% 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
% 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♠
%
i
0 1 2 3 4 5 6 7 8 9 10 11 12
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 ...
deck 2♣ 2♦ 2♥ 2♠ 3♣ 3♦ 3♥ 3♠ 4♣ 4♦ 4♥ 4♠ 5♣ ...
20
21
Array application: take a card, any card
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].
for (int i = 0; i < N; i++) each value between 0 and 5 1 equally likely
{
int r = (int) ([Link]() 52);
[Link](deck[r]);
}
Note: Same method is effective for printing a random sequence from any data collection.
22
Array application: random sequence of cards
String[] rank = {"2", "3", "4", "5", "6", "7", "8", "9","10", "J", "Q", "K", "A" };
String[] suit = { "♣", "♦", "♥", "♠" };
Note: Sample is with replacement (same card can appear multiple times). appears twice
23
Array application: shuffle and deal from a deck of cards
24
Array application: shuffle a deck of 10 cards (trace)
deck
i r
for (int i = 0; i < 10; i++) 0 1 2 3 4 5 6 7 8 9
{
int r = i + (int) ([Link]() (10-i)); 2♣ 3♣ 4♣ 5♣ 6♣ 7♣ 8♣ 9♣ 10♣ J♣
String t = deck[r];
0 7 9♣ 3♣ 4♣ 5♣ 6♣ 7♣ 8♣ 2♣ 10♣ J♣
deck[r] = deck[i];
deck[i] = t; 1 3 9♣ 5♣ 4♣ 3♣ 6♣ 7♣ 8♣ 2♣ 10♣ J♣
}
2 9 9♣ 5♣ J♣ 3♣ 6♣ 7♣ 8♣ 2♣ 10♣ 4♣
9 9 9♣ 5♣ J♣ 4♣ 8♣ 3♣ 10♣ 7♣ 6♣ 2♣
Note: Same method is effective for randomly rearranging any type of data.
25
Array application: shuffle and deal from a deck of cards
String[] rank = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A" };
String[] suit = { "♣", "♦", "♥", "♠" };
Sequence
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 2 cards needed
to complete
2♦ 5♦ 8♣ 9♥ 10♥ Q♥ A♦ collection
9♣ 10♥
27
Array application: coupon collector
% java Coupon 13
value in the array. } 22
28
Array application: coupon collector (trace for M = 6)
found
r distinct cards
0 1 2 3 4 5
F F F F F F 0 0
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
29
Simulation, randomness, and analysis (revisited)
type M M ln M + .57721M
% java CouponCollector 4 1000000
playing card suits 4 8 8
grade
Examples 0 1 2 3 4 5 ...
student ID
2 C D D B C A
• Geographic data
• ...
y-coordinate
Main purpose. Facilitate storage and manipulation of data.
x-coordinate 35
Java language support for two-dimensional arrays (basic support)
a[][]
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] 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]
a 3-by-10 array
36
Java language support for two-dimensional arrays (initialization)
double[][] p=
{
{ .92, .02, .02, .02, .02 },
{ .02, .92, .32, .32, .32 },
Initialize to literal values { .02, .02, .02, .92, .02 },
{ .92, .02, .02, .02, .02 },
{ .47, .02, .47, .02, .02 },
};
37
Application of arrays: vector and matrix calculations
38
Application of arrays: vector and matrix calculations
end-of-loop trace
39
Pop quiz 4 on arrays
1. N
2. N2
3. N3
4. N4
40
Pop quiz 4 on arrays
1. N
2. N2
3. N3 Nested forloops: N × N × N
4. N4
41
Self-avoiding random walks
A d o g walks around at
random in a city, never
revisiting any intersection.
escape
Model: 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.
Approach: Use Monte Carlo simulation, recording visited positions in an N-by-N array.
42
Self-avoiding random walks
43
Application of 2D arrays: self-avoiding random walks
}
[Link](100 deadEnds/trials + "% dead ends"); 50%
}
} 25%
0%
10 20 30 40 50 60 70 80 90 100
44
Simulation, randomness, and analysis (revisited again)
Mathematicians and
A. Nobody knows (despite decades of study). physics researchers
cannot solve the problem.
Computational models play
A. 9 9 + % for N > 1 0 0 (clear from simulations). YOU can! an essential role in modern
scientific research.
Remark: Computer simulation is often the only effective way to study a scientific phenomenon.
45
Your first data structure
LFSR
digital audio
46
Image sources
[Link]
[Link]