1.3 Conditionals and Loops



Similar documents
1.4 Arrays Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright /6/11 12:33 PM!

Lecture 2 Notes: Flow of Control

Iteration CHAPTER 6. Topic Summary

Statements and Control Flow

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

VB.NET Programming Fundamentals

Example of a Java program

LOOPS CHAPTER CHAPTER GOALS

Conditional Statements Summer 2010 Margaret Reid-Miller

Object Oriented Software Design

PIC 10A. Lecture 7: Graphics II and intro to the if statement

5.2 Q2 The control variable of a counter-controlled loop should be declared as: a.int. b.float. c.double. d.any of the above. ANS: a. int.

Roots of Equations (Chapters 5 and 6)

Informatica e Sistemi in Tempo Reale

CS170 Lab 11 Abstract Data Types & Objects

Exercise 1: Python Language Basics

ALGORITHMS AND FLOWCHARTS

CSC 221: Computer Programming I. Fall 2011

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

J a v a Quiz (Unit 3, Test 0 Practice)

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

1.1 Your First Program

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June Dr.-Ing.

Building Java Programs

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Chapter 2: Algorithm Discovery and Design. Invitation to Computer Science, C++ Version, Third Edition

TIP: To access the WinRunner help system at any time, press the F1 key.

Topic 11 Scanner object, conditional execution

Introduction to Java

Interactive Applications (CLI) and Math

6. Control Structures

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

Chapter 4 Lecture Notes

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Computer Programming I

Random Fibonacci-type Sequences in Online Gambling

1. (First passage/hitting times/gambler s ruin problem:) Suppose that X has a discrete state space and let i be a fixed state. Let

Euler s Method and Functions

Two-way selection. Branching and Looping

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Unit 6. Loop statements

CS1010 Programming Methodology A beginning in problem solving in Computer Science. Aaron Tan 20 July 2015

IRA EXAMPLES. This topic has two examples showing the calculation of the future value an IRA (Individual Retirement Account).

Term Project: Roulette

River Dell Regional School District. Computer Programming with Python Curriculum

Sample CSE8A midterm Multiple Choice (circle one)

#820 Computer Programming 1A

Cohort: BCA/07B/PT - BCA/06/PT - BCNS/06/FT - BCNS/05/FT - BIS/06/FT - BIS/05/FT - BSE/05/FT - BSE/04/PT-BSE/06/FT

Decision Making under Uncertainty

Computer Programming I

PHP Tutorial From beginner to master

Lecture Notes on Linear Search

Building Java Programs

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

1. Then f has a relative maximum at x = c if f(c) f(x) for all values of x in some

Pseudo code Tutorial and Exercises Teacher s Version

In this Chapter you ll learn:

While and Do-While Loops Summer 2010 Margaret Reid-Miller

Stochastic Processes and Advanced Mathematical Finance. Ruin Probabilities

6. Standard Algorithms

Notes on Continuous Random Variables

Object Oriented Software Design

Lecture 13: Martingales

Computational Mathematics with Python

JavaScript Introduction

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

CHM 579 Lab 1: Basic Monte Carlo Algorithm

Discrete Math in Computer Science Homework 7 Solutions (Max Points: 80)

AMS 5 CHANCE VARIABILITY

Exercise 4 Learning Python language fundamentals

Sources: On the Web: Slides will be available on:

Overview. java.math.biginteger, java.math.bigdecimal. Definition: objects are everything but primitives The eight primitive data type in Java

Wald s Identity. by Jeffery Hein. Dartmouth College, Math 100

Introduction to Matrices

Some programming experience in a high-level structured programming language is recommended.

Chapter 8 Selection 8-1

MTH6120 Further Topics in Mathematical Finance Lesson 2

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

While Loop. 6. Iteration

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

Introduction to Python

Summit Public Schools Summit, New Jersey Grade Level / Content Area: Mathematics Length of Course: 1 Academic Year Curriculum: AP Computer Science A

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0

Computational Mathematics with Python

Software Development. Chapter 7. Outline The Waterfall Model RISKS. Java By Abstraction Chapter 7

1.00/ Session 2 Fall Basic Java Data Types, Control Structures. Java Data Types. 8 primitive or built-in data types

Quosal Form Designer Training Documentation

API for java.util.iterator. ! hasnext() Are there more items in the list? ! next() Return the next item in the list.

Now is the time. For all good men PERMUTATION GENERATION. Princeton University. Robert Sedgewick METHODS

Binary Number System. 16. Binary Numbers. Base 10 digits: Base 2 digits: 0 1

Arrays. Introduction. Chapter 7

Programming Database lectures for mathema

2.3 WINDOW-TO-VIEWPORT COORDINATE TRANSFORMATION

Stochastic Processes and Advanced Mathematical Finance. Duration of the Gambler s Ruin

1. Overconfidence {health care discussion at JD s} 2. Biased Judgments. 3. Herding. 4. Loss Aversion

SOME ASPECTS OF GAMBLING WITH THE KELLY CRITERION. School of Mathematical Sciences. Monash University, Clayton, Victoria, Australia 3168

Expected Value and the Game of Craps

Building Java Programs

Transcription:

A Foundation for Programming 1.3 Conditionals and Loops any program you might want to write objects functions and modules graphics, sound, and image I/O arrays conditionals and loops Math primitive data types text I/O assignment statements last lecture: equivalent to a calculator Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright 00 010 19 May 01 1:45:09 A Foundation for Programming Control Flow any program you might want to write Control flow Sequence of statements that are actually executed in a program Conditionals and loops: enable us to choreograph control flow objects boolean 1 functions and modules graphics, sound, and image I/O arrays statement statement 3 boolean statement conditionals and loops to infinity and beyond! Math text I/O statement 4 primitive data types assignment statements straight-line control flow statement 3 control flow with conditionals and loops 3 4 If Statement Conditionals The if statement A common branching structure If, execute some statements If, execute other statements if (boolean expression) { statement T; can be any sequence of statements statement F; boolean expression statement T statement F 6 1

If Statement If Statement The if statement A common branching structure If, execute some statements If, execute other statements Ex. Take different action depending on value of variable. public class Flip { if (Math.random() < 0.5) System.out.println("Heads"); else System.out.println("Tails"); Heads Heads Tails Heads 7 8 If Statement Examples The For Loop Copyright 004, FoxTrot by Bill Amend www.ucomics.com/foxtrot/003/10/03 9 10 For Loops Anatomy of a For Loop The for loop A common repetition structure Execute initialization statement If, execute some statements And then the increment statement Repeat loop continuation condition for (init; boolean expression; increment) { ; statement ; body init increment statement shorthand for i = i +1 boolean expression Q. What does it print? A. 11 1

For Loop: Powers of Two For Loops: Subdivisions of a Ruler Ex. Print powers of that are Increment i from 0 to N Double v each time N Create subdivision of a ruler Initialize ruler to " " For each value i from 1 to N: i v i <= N sandwich two copies of ruler on either side of i 1 4 5 3 7 18 1 4 5 3 public class RulerN { int N = Integer.parseInt(args[0]); String ruler = " "; for (int i = 1; i <= N; i++) { ruler = ruler + i + ruler; System.out.println(ruler); i ruler " " 1 " 1 " " 1 1 " 3 " 1 1 3 1 1 " N = 6 Click for demo 13 14 For Loops: Subdivisions of a Ruler % java RulerN 1 1 The While Loop % java RulerN 1 1 % java RulerN 3 1 1 3 1 1 % java RulerN 4 1 1 3 1 1 4 1 1 3 1 1 % java RulerN 5 1 1 3 1 1 4 1 1 3 1 1 5 1 1 3 1 1 4 1 1 3 1 1 % java RulerN 100 Exception in thread "main" java.lang.outofmemoryerror Observation Loops can produce a huge amount of output! 15 16 While Loop While Loop: Powers of Two The while loop. Another common repetition structure If, execute some statements Repeat Ex. Print powers of that are Increment i from 0 to N Double v each time N i v i <= N loop continuation condition statement while (boolean expression) { ; loop body statement ; boolean expression int i = 0; int v = 1; while (i <= N) { i++; v = * v; 1 4 5 3 1 4 5 3 7 18 N = 6 Click for demo 17 18 3

Powers of Two While Loop Challenge Q. Anything wrong with the following code for printing powers of? public class PowersOfTwo { // 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) { i = i + 1; v = * v; print i and ith power of two % java PowersOfTwo 3 1 4 % java PowersOfTwo 6 1 4 5 3 int i = 0; int v = 1; while (i <= N) i = i + 1; v = * v; 19 0 While Loop Challenge While Loops: Square Root Q. Anything wrong with the following code for printing powers of? Goal. Implement Math.sqrt() % java Sqrt.0 1.4141356373095 int i = 0; int v = 1; while (i <= N) i = i + 1; v = * v; Newton-Raphson method 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 15 decimal digits of accuracy in 5 iterations A. Need curly braces around statements in while loop; otherwise it enters an infinite loop, printing "". Moment of panic. How to stop infinite loop? t 0.0 t 1 1 0 t 1 1 t 3 1 t 4 1 3 t 5 1 4 t 0 ) 1.5 t 1 ) 1.416666666666665 t ) 1.41415686745097 t 3 ) 1.41413563746899 t 4 ) 1.4141356373095 computing the square root of Copyright 004, Sidney Harris www.sciencecartoonsplus.com 1 While Loops: Square Root Newton-Raphson Method Goal. Implement Math.sqrt(). % java Sqrt.0 1.4141356373095 Square root method explained Goal: find root of any function f(x) Newton-Raphson method 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. 15 decimal digits of accuracy in 5 iterations Start with estimate t 0 f(x) = x - c to compute c 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 public class Sqrt { 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) /.0; relative error System.out.println(t); tolerance Technical conditions. f(x) is smooth; t 0 is good estimate 3 4 4

Loop Examples Nesting 5 6 Nested If Statements Nested If Statements Ex. Pay a certain tax rate depending on income level Use nested if statements to handle multiple alternatives Income Rate 0-47,450 % 47,450 114,650 5% 114,650 174,700 8% 174,700 311,950 33% 311,950-35% double rate; if (income < 47450) rate = 0.; else if (income < 114650) rate = 0.5; else if (income < 174700) rate = 0.8; else if (income < 311950) rate = 0.33; 5 mutually exclusive alternatives if (income < 47450) rate = 0.; if (income < 114650) rate = 0.5; if (income < 174700) rate = 0.8; if (income < 311950) rate = 0.33; graduated income tax calculation 8 9 Nested If Statements Nested If Statement Challenge Need all those braces? Not always Q. What's wrong with the following for income tax calculation? if (income < 47450) rate = 0.; else if (income < 114650) rate = 0.5; else if (income < 174700) rate = 0.8; else if (income < 311950) rate = 0.33; Income Rate 0-47,450 % 47,450 114,650 5% is shorthand for if (income < 47450) rate = 0.; if (income < 114650) rate = 0.5; if (income < 174700) rate = 0.8; if (income < 311950) rate = 0.33; 114,650 174,700 8% 174,700 311,950 33% 311,950-35% double rate = 0.35; if (income < 47450) rate = 0.; if (income < 114650) rate = 0.5; if (income < 174700) rate = 0.8; if (income < 311950) rate = 0.33; but be careful when nesting if-else statements. [See Q+A on p. 75.] wrong graduated income tax calculation 30 31 5

Gambler's Ruin Monte Carlo Simulation 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 3 33 Gambler's Ruin Digression: Simulation and Analysis public class Gambler { int stake = Integer.parseInt(args[0]); int goal = Integer.parseInt(args[1]); int T = Integer.parseInt(args[]); int wins = 0; // repeat experiment T times for (int t = 0; t < T; t++) { // do one gambler's ruin experiment int cash = stake; while (cash > 0 && cash < goal) { // flip coin and update if (Math.random() < 0.5) cash++; else cash--; if (cash == goal) wins++; System.out.println(wins + " wins of " + T); stake goal T % java Gambler 5 5 1000 191 wins of 1000 % java Gambler 5 5 1000 03 wins of 1000 % java Gambler 500 50000 197 wins of 1000 after a substantial wait. Fact Probability of winning = stake goal Fact Expected number of bets = stake desired gain Ex. 0% chance of turning $500 into $500, 500/500 = 0% but expect to make one million $1 bets 500 * (500-500) = 1 million Remark Both facts can be proved mathematically; for more complex scenarios, computer simulation is often the best (only) plan of attack 34 35 Control Flow Summary Control flow Sequence of statements that are actually executed in a program Conditionals and loops: enable us to choreograph the control flow Control Flow Description Examples straight-line programs conditionals loops all statements are executed in the order given certain statements are executed depending on the values of certain variables certain statements are executed repeatedly until certain conditions are met if if-else while for do-while 36 6