

























Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


























!
2
objects functions and modules graphics, sound, and image I/O arrays conditionals and loops Math text I/O primitive data types assignment statements last lecture: equivalent to a calculator any program you might want to write
4
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
7
8
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"); } } % java Flip Heads % java Flip Heads % java Flip Tails % java Flip Heads
10
11
while ( boolean expression ) { statement 1 ; statement 2 ; } statement 1 true false boolean expression statement 2 loop body loop continuation condition
13
public class PowersOfTwo { public static void main(String[] args) { // last power of two to print int N = Integer.parseInt(args[ 0 ]); int i = 0 ; // loop control counter int v = 1 ; // current power of two while (i <= N) { System.out.println(i + " " + v); i = i + 1 ; v = 2 * v; } } } % java PowersOfTwo 3 0 1 1 2 2 4 3 8 % java PowersOfTwo 6 0 1 1 2 2 4 3 8 4 16 5 32 6 64 print i and ith power of two
14
int i = 0 ; int v = 1 ; while (i <= N) System.out.println(i + " " + v); i = i + 1 ; v = 2 * v;
17 public class Sqrt { public static void main(String[] args) { double epsilon = 1e-15; double c = Double.parseDouble(args[ 0 ]); double t = c; while (Math.abs(t - c/t) > t*epsilon) { t = (c/t + t) / 2.0; } System.out.println(t); } } % java Sqrt 2.
relative error tolerance 15 decimal digits of accuracy in 5 iterations
18
f(x) = x^2 - c to compute "c
20
for ( init ; boolean expression ; increment ) { statement 1 ; statement 2 ; } statement 1 true false boolean expression statement 2 init increment body loop continuation condition
21