# 1.3 conditionals and loops - princeton conditionals and loops math text i/o primitive data types...     Post on 16-Oct-2019

0 views

Category:

## Documents

Embed Size (px)

TRANSCRIPT

• !1

! ! !

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

1.3 Conditionals and Loops

to infinity and beyond!

conditionals and loops

!4

Conditionals and Loops

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

!5

Conditionals

!6

• If Statement

The if statement. A common branching structure.

• Evaluate a boolean expression. • If true, execute some statements. •else option: If false, execute other statements.

if ( x > y ) { int t = x; x = y; y = t; }

sequence of

statements

boolean expression yes no

yes no

!7

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"); else System.out.println("Tails"); } }

% java Flip

!8

If Statement Examples

if (x < 0) x = -x;

absolute value

if (x > y) max = x;   else max = y;

maximum

if (den == 0) System.out.println("Division by zero");  else System.out.println("Quotient = " + num/den);

error check for division operation

double discriminant = b*b - 4.0*c;   if (discriminant < 0.0)   {   System.out.println("No real roots");   }   else   {   System.out.println((-b + Math.sqrt(discriminant))/2.0);  System.out.println((-b - Math.sqrt(discriminant))/2.0);  }

if (x > y)   {   int t = x;   x = y;   y = t;   }

2-sort

x y t

1234 99 undefined

1234 99 1234

99 99 1234

99 1234 1234

x < y after

x > y before

!9

Loops

!10

• While Loop

The while loop. A common repetition structure.

• Check a boolean expression. • Execute a sequence of statements. • Repeat.

while (boolean expression) { statement 1; statement 2; }

statement 1 true

false

boolean expression

statement 2

loop body

loop continuation condition

!11

While Loop Example: Powers of Two

int i = 0; int v = 1; while (i

• While Loop Example: Square Root

% java Sqrt 60481729 7777.0

computing the square root of 2 to seven places

i t 2/t 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

2.0

1.0

Goal. Implement Math.sqrt().   Newton-Raphson method to compute the square root of 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.

!52

public class Sqrt { public static void main(String[] args) { double EPS = 1E-15; double c = Double.parseDouble(args); double t = c; while (Math.abs(t - c/t) > t * EPS) { t = (c/t + t) / 2.0; } System.out.println(t); } } % java Sqrt 2.0

1.414213562373095

error tolerance

15 decimal digits of accuracy in 5 iterations

While Loop Example: Square Root

Goal. Implement Math.sqrt().   Newton-Raphson method to compute the square root of 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.

!53

Newton-Raphson Method

Square root method explained (some math omitted).

• Goal: find root of function f(x). • 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.

f(x) = x2 - c to compute √c

!54

The For Loop

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

!55

• The for loop. Another common repetition structure.

• Execute initialization statement. • Check boolean expression. • Execute sequence of statements. • Execute increment statement. • Repeat.

The For Loop

for (init; boolean expression; increment) { statement 1; statement 2; }

increment

true

false

boolean expression

statement 2

init

statement 1 body

loop continuation condition

!56

Anatomy of a for Loop

int v = 1; for ( int i = 0; i

• ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! Observation. Loops can produce a huge amount of output!

% 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

2100 - 1 = 1,267,650,600,228,229,401,496,703,205,375 integers in output

!60

Loop Examples

int sum = 0; for (int i = 1; i

• Nested If Statements

Ex. Pay a certain tax rate depending on income level.

0 - 47,450 22%

Income Rate

47,450 – 114,650 25%

114,650 – 174,700 28%

174,700 – 311,950 33%

311,950 - 35%

5 mutually exclusive alternatives

!64

Use nested if statements to handle multiple alternatives

Nested If Statements

if (income < 47450) rate = 0.22; 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; } } }

!65

Use nested if statements to handle multiple alternatives

Nested If-Else Statements

if (income < 47450) rate = 0.22; 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; } } }

if statement within an if statement

!66

Use nested if statements to handle multiple alternatives

Nested If-Else Statements

if (income < 47450) rate = 0.22; 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; } } }

if statement within an if statement within an if statement

!67

• Use nested if statements to handle multiple alternatives

Nested If-Else Statements

if (income < 47450) rate = 0.22; 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; } } }

if statement within an if statement within an if statement within an if statement

!68

Need all those braces? Not always: ! ! ! ! ! ! is shorthand for ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! but BE CAREFUL when nesting if-else statements (see Q&A p. 75).

Nested If-Else Statements

if (income < 47450) rate = 0.22; 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;

if (income < 47450) rate = 0.22; 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; } } }

!69

Nested If Statement Challenge

Anything wrong with the following code?

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;

!70

Ex. Visit each location in a two-dimensional table (stay tuned for arrays). ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) Do something at entry (i,j);

Nested for loops

0 M-1

0

N-1

j

i

Recommended