{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

1.3flow

# 1.3flow - A Foundation for Programming 1.3 Conditionals and...

This preview shows pages 1–4. Sign up to view the full content.

1.3 Conditionals and Loops 2 A Foundation for Programming objects functions and modules graphics, sound, and image I/O arrays conditionals and loops Math text I/O assignment statements primitive data types equivalent to a calculator any program you might want to write 4 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 Math.random() < 0.5) System . out . println ( "Tails" ); } } 5 If Statement Examples

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
6 The While Loop 7 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 8 While Loops: Powers of Two Ex. Print first n powers of 2. ! Increment i from 1 to n . ! Double v each time. Click for demo int i = 0 ; int v = 1 ; while ( i <= N ) { System . out . println ( v ); i = i + 1 ; v = 2 * v ; } % java Powers 1 2 4 8 16 32 64 0 1 i v 1 2 2 4 3 8 true i <= N true true true 4 16 5 32 6 64 7 128 true true true false n = 6 9 While Loop Challenge Q. Anything wrong with the following code for printing powers of 2? int i = 0 ; int v = 1 ; while ( i <= N ) System . out . println ( v ); i = i + 1 ; v = 2 * v ;
12 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.0 1.414213562373095 error tolerance 15 decimal digits of accuracy in 5 iterations 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 t i = c / t i , up to desired precision: set t i+1 to be the average of t i and c / t i . 13 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= t i . ! Set t i+1 to be x-coordinate where line hits x-axis. ! Repeat until desired precision. f(x) = x 2 - c to compute ! c 14 The For Loop Copyright 2004, FoxTrot by Bill Amend www.ucomics.com/foxtrot/2003/10/03 15 For Loops The for loop. Another common repetition structure.

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}