Docsity

Control Flow: Sequence, If-Else Statements, and Loops in Java, Study notes of Computer Science

Toggle sidebar
bg1
1.3 Conditionals and Loops
Copyright 2004, FoxTrot by Bill Amend
www.ucomics.com/foxtrot/2003/10/03
2
Control Flow
Control flow.
!Sequence of statements that are actually executed in a program.
!Conditionals and loops: enable us to choreograph control flow.
statement 2
statement 1
statement 4
statement 3 boolean 2 true
false
statement 2
boolean 1
statement 3
false
statement 1
true
straight-line control flow control flow with conditionals and loops
Conditionals
4
If Statement
The if statement. A common branching structure.
!Check boolean condition.
!If true, execute some statements.
!If false, execute other statements.
if (boolean expression) {
statement T;
}
else {
statement F;
}
can be any sequence
of statements
statement T
true false
boolean expression
statement F
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Control Flow: Sequence, If-Else Statements, and Loops in Java and more Study notes Computer Science in PDF only on Docsity!

1.3 Conditionals and Loops

Copyright 2004, FoxTrot by Bill Amend www.ucomics.com/foxtrot/2003/10/ 2

Control Flow

Control flow.

! Sequence of statements that are actually executed in a program.

! Conditionals and loops: enable us to choreograph control flow.

statement 2 statement 1 statement 4 statement 3 boolean 2^ true false statement 2 boolean 1 statement 3 false statement 1 true straight-line control flow control flow with conditionals and loops

Conditionals

If Statement

The if statement. A common branching structure.

! Check boolean condition.

! If true, execute some statements.

! If false, execute other statements.

if (boolean expression) { statement T; } else { statement F; } can be any sequence of statements statement T true false boolean expression statement F

5

If Statement

The if statement. A common branching structure.

! Check boolean condition.

! If true, execute some statements.

! If false, execute other statements.

6

If Statement

Ex. Take different action depending on value of variable.

public class Flip { public static void main(String[] args) { if (Math.random() < 0.5) System.out.println("Heads"); elseMath.random() < 0.5) System.out.println("Tails"); } }

If Statement Examples

The While Loop

13

While Loops: Square Root

Q. How might we implement Math.sqrt()?

A. To compute the square root of c:

! Initialize t 0 = c.

! Repeat until ti = c / ti, up to desired precision:

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

t 0 = 2. t 1 = 12 ( t 0 + (^) t^20 ) = 1. t 2 = 12 ( t 1 + (^) t^21 ) = 1. t 3 = 12 ( t 2 + (^) t^22 ) = 1. t 4 = 12 ( t 3 + (^) t^23 ) = 1. t 5 = 12 ( t 4 + (^) t^24 ) = 1. computing the square root of 2

Q. How might we implement Math.sqrt()?

A. To compute the square root of c:

! Initialize t 0 = c.

! Repeat until ti = c / ti, up to desired precision:

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

14 public class Sqrt { public static void main(String[] args) { double EPS = 1E-15; 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); } } % java Sqrt 2.

error tolerance 15 decimal digits of accuracy in 5 iterations

While Loops: Square Root

Newton-Raphson Method

Square root method explained.

! Goal: find root of function f(x).

! Start with estimate t 0.

! Draw line tangent to curve at x= ti.

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

! Repeat until desired precision.

f(x) = x^2 - c to compute !c

The For Loop

17 For Loops

The for loop. Another common repetition structure.

! Execute initialization statement.

! Check boolean expression.

! Execute sequence of statements.

! Execute increment statement.

! Repeat.

for (init; boolean expression; increment) { statement 1; statement 2; } true statement 1 false boolean expression statement 2 init increment body loop continuation condition 18 For Loops: Subdivisions of a Ruler

Create subdivision of a ruler.

! Initialize ruler to empty string.

! For each value i from 1 to N:

sandwich two copies of ruler on either side of i.

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); } } 1 " 1 " i ruler 2 " 1 2 1 " 3 " 1 2 1 3 1 2 1 " " " % java Ruler 1 1 % java Ruler 2 1 2 1 % java Ruler 3 1 2 1 3 1 2 1 % java Ruler 4 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 % java Ruler 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 % java Ruler 100 Exception in thread "main" java.lang.OutOfMemoryError For Loops: Subdivisions of a Ruler

Observation. Loops can produce a huge amount of output!

Loop Examples

25

Monte Carlo Simulation

26

Gambler's Ruin

Gambler's ruin. Gambler starts with $stake and places $1 fair bets

until going broke or reaching $goal.

! What are the chances of winning?

! How many bets will it take?

One approach. Monte Carlo simulation.

! Flip digital coins and see what happens.

! Repeat and compute statistics.

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 ; System.out.println(wins + " wins of " + trials); } } // repeat experiment N times for (int i = 0 ; i < trials; i++) { } // do one gambler's ruin experiment int t = stake; while (t > 0 && t < goal) { } if (t == goal) wins++; // flip coin and update if (Math.random() < 0.5) t++; else t--;

Gambler's Ruin

Simulation and Analysis

Fact. Probability of winning = stake ÷ goal.

Fact. Expected number of bets = stake " desired gain.

Ex. 20% chance of turning $500 into $2500, but expect

to make one million $1 bets.

Remark. Both facts can be proved mathematically; for more complex

scenarios, computer simulation is often the best plan of attack.

% java Gambler 5 25 1000 191 wins of 1000 % java Gambler 5 25 1000 203 wins of 1000 % java Gambler 500 2500 1000 197 wins of 1000 stake goal trials after a few hours of computing….

29

Debugging

http://www.history.navy.mil/photos/images/h96000/h96566kc.htm Admiral Grace Murray Hopper 30

Debugging a Program

Factor. Given an integer N, compute its prime factorization.

Application. Break RSA cryptosystem.

3,757,208 = 2^3 " 7 " 132 " 397

3757208/

Debugging a Program: Syntax Errors

Syntax error. Illegal Java program.

! Compiler error messages help locate problem.

! Eventually, a file named Factors.class.

public class Factors1 { 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 } } } As long as i is a factor, divide it out. Check if i is a factor. Compile-time error

Debugging a Program: Semantic Errors

Semantic error. Legal but wrong Java program.

! Use "System.out.println" method to identify problem.

public class Factors2 { public static void main(String[] args) { long N = Long.parseLong(args[ 0 ]); for (long i = 2 ; i < N; i++) { while (N % i == 0 ) System.out.print(i + " "); N = N / i; } } } As long as i is a factor, divide it out. Check if i is a factor. no output (17) or infinite loop (49) Run-time error

37 Programming in Java

Programming in Java. [a slightly more realistic view]

1. Create the program.

2. Compile it..

Compiler says: That’s not a legal program.

Back to step 1 to fix your errors of syntax.

3. Execute it.

Result is bizarrely (or subtly) wrong.

Back to step 1 to fix your errors of semantics.

4. Enjoy the satisfaction of a working program!

38 Debugging a Program

Debugging. Cyclic process of editing, compiling, and fixing errors.

! Always a logical explanation.

! What would the machine do?

! Explain it to the teddy bear.

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

As soon as we started programming, we found out to our surprise that it wasn't as easy to get programs right as we had thought. I can remember the exact instant when I realized that a large part of my life from then on was going to be spent in finding mistakes in my own programs. - Maurice Wilkes If I had 8 hours to chop down a tree, I would spend 6 hours sharpening an axe. - Abraham Lincoln Control Flow Summary

Control flow.

! Sequence of statements that are actually executed in a program.

! Conditionals and loops: enables us to choreograph the control flow.

Straight-line programs All statements are executed in the order given. Conditionals Certain statements are executed depending on the values of certain variables. if if-else Loops Certain statements are executed repeatedly until certain conditions are met. while for do-while Control Flow Description Examples