1.3 Conditionals and Loops

Size: px
Start display at page:

Download "1.3 Conditionals and Loops"

Transcription

1 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 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

2 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 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

3 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 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 " " N = 6 Click for demo For Loops: Subdivisions of a Ruler % java RulerN 1 1 The While Loop % java RulerN 1 1 % java RulerN % java RulerN % java RulerN % java RulerN 100 Exception in thread "main" java.lang.outofmemoryerror Observation Loops can produce a huge amount of output! 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; N = 6 Click for demo

4 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 % java PowersOfTwo 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 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 t 1 1 t 3 1 t t t 0 ) 1.5 t 1 ) t ) t 3 ) t 4 ) computing the square root of Copyright 004, Sidney Harris 1 While Loops: Square Root Newton-Raphson Method Goal. Implement Math.sqrt(). % java Sqrt 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

5 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, ,650 5% 114, ,700 8% 174, ,950 33% 311,950-35% double rate; if (income < 47450) rate = 0.; else if (income < ) rate = 0.5; else if (income < ) rate = 0.8; else if (income < ) rate = 0.33; 5 mutually exclusive alternatives if (income < 47450) rate = 0.; if (income < ) rate = 0.5; if (income < ) rate = 0.8; if (income < ) 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 < ) rate = 0.5; else if (income < ) rate = 0.8; else if (income < ) rate = 0.33; Income Rate 0-47,450 % 47, ,650 5% is shorthand for if (income < 47450) rate = 0.; if (income < ) rate = 0.5; if (income < ) rate = 0.8; if (income < ) rate = 0.33; 114, ,700 8% 174, ,950 33% 311,950-35% double rate = 0.35; if (income < 47450) rate = 0.; if (income < ) rate = 0.5; if (income < ) rate = 0.8; if (income < ) rate = 0.33; but be careful when nesting if-else statements. [See Q+A on p. 75.] wrong graduated income tax calculation

6 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 wins of 1000 % java Gambler wins of 1000 % java Gambler 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 * ( ) = 1 million Remark Both facts can be proved mathematically; for more complex scenarios, computer simulation is often the best (only) plan of attack 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

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

1.4 Arrays Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright 2002 2010 2/6/11 12:33 PM! 1.4 Arrays Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright 2002 2010 2/6/11 12:33 PM! A Foundation for Programming any program you might want

More information

Lecture 2 Notes: Flow of Control

Lecture 2 Notes: Flow of Control 6.096 Introduction to C++ January, 2011 Massachusetts Institute of Technology John Marrero Lecture 2 Notes: Flow of Control 1 Motivation Normally, a program executes statements from first to last. The

More information

Iteration CHAPTER 6. Topic Summary

Iteration CHAPTER 6. Topic Summary CHAPTER 6 Iteration TOPIC OUTLINE 6.1 while Loops 6.2 for Loops 6.3 Nested Loops 6.4 Off-by-1 Errors 6.5 Random Numbers and Simulations 6.6 Loop Invariants (AB only) Topic Summary 6.1 while Loops Many

More information

Statements and Control Flow

Statements and Control Flow Contents 1. Introduction 2. Types and Variables 3. Statements and Control Flow 4. Reading Input 5. Classes and Objects 6. Arrays 7. Methods 8. Scope and Lifetime 9. Utility classes 10. Introduction to

More information

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

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 Oct 4, 2013, p 1 Name: CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 1. (max 18) 4. (max 16) 2. (max 12) 5. (max 12) 3. (max 24) 6. (max 18) Total: (max 100)

More information

VB.NET Programming Fundamentals

VB.NET Programming Fundamentals Chapter 3 Objectives Programming Fundamentals In this chapter, you will: Learn about the programming language Write a module definition Use variables and data types Compute with Write decision-making statements

More information

Example of a Java program

Example of a Java program Example of a Java program class SomeNumbers static int square (int x) return x*x; public static void main (String[] args) int n=20; if (args.length > 0) // change default n = Integer.parseInt(args[0]);

More information

LOOPS CHAPTER CHAPTER GOALS

LOOPS CHAPTER CHAPTER GOALS jfe_ch04_7.fm Page 139 Friday, May 8, 2009 2:45 PM LOOPS CHAPTER 4 CHAPTER GOALS To learn about while, for, and do loops To become familiar with common loop algorithms To understand nested loops To implement

More information

Conditional Statements. 15-110 Summer 2010 Margaret Reid-Miller

Conditional Statements. 15-110 Summer 2010 Margaret Reid-Miller Conditional Statements 15-110 Summer 2010 Margaret Reid-Miller Conditional statements Within a method, we can alter the flow of control (the order in which statements are executed) using either conditionals

More information

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa September 14, 2011 G. Lipari (Scuola Superiore Sant Anna) Introduction

More information

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

PIC 10A. Lecture 7: Graphics II and intro to the if statement PIC 10A Lecture 7: Graphics II and intro to the if statement Setting up a coordinate system By default the viewing window has a coordinate system already set up for you 10-10 10-10 The origin is in the

More information

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.

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. Java How to Program, 5/e Test Item File 1 of 5 Chapter 5 Section 5.2 5.2 Q1 Counter-controlled repetition requires a.a control variable and initial value. b.a control variable increment (or decrement).

More information

Roots of Equations (Chapters 5 and 6)

Roots of Equations (Chapters 5 and 6) Roots of Equations (Chapters 5 and 6) Problem: given f() = 0, find. In general, f() can be any function. For some forms of f(), analytical solutions are available. However, for other functions, we have

More information

Informatica e Sistemi in Tempo Reale

Informatica e Sistemi in Tempo Reale Informatica e Sistemi in Tempo Reale Introduction to C programming Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 25, 2010 G. Lipari (Scuola Superiore Sant Anna)

More information

CS170 Lab 11 Abstract Data Types & Objects

CS170 Lab 11 Abstract Data Types & Objects CS170 Lab 11 Abstract Data Types & Objects Introduction: Abstract Data Type (ADT) An abstract data type is commonly known as a class of objects An abstract data type in a program is used to represent (the

More information

Exercise 1: Python Language Basics

Exercise 1: Python Language Basics Exercise 1: Python Language Basics In this exercise we will cover the basic principles of the Python language. All languages have a standard set of functionality including the ability to comment code,

More information

ALGORITHMS AND FLOWCHARTS

ALGORITHMS AND FLOWCHARTS ALGORITHMS AND FLOWCHARTS A typical programming task can be divided into two phases: Problem solving phase produce an ordered sequence of steps that describe solution of problem this sequence of steps

More information

CSC 221: Computer Programming I. Fall 2011

CSC 221: Computer Programming I. Fall 2011 CSC 221: Computer Programming I Fall 2011 Python control statements operator precedence importing modules random, math conditional execution: if, if-else, if-elif-else counter-driven repetition: for conditional

More information

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

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority) Boolean Expressions, Conditions, Loops, and Enumerations Relational Operators == // true if two values are equivalent!= // true if two values are not equivalent < // true if left value is less than the

More information

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

J a v a Quiz (Unit 3, Test 0 Practice) Computer Science S-111a: Intensive Introduction to Computer Science Using Java Handout #11 Your Name Teaching Fellow J a v a Quiz (Unit 3, Test 0 Practice) Multiple-choice questions are worth 2 points

More information

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

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language Translation Translating to Java Introduction to Computer Programming The job of a programmer is to translate a problem description into a computer language. You need to be able to convert a problem description

More information

1.1 Your First Program

1.1 Your First Program Why Programming? 1.1 Your First Program Why programming? Need to tell computer what you want it to do. Naive ideal. Natural language instructions. Please simulate the motion of N heavenly bodies, subject

More information

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

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements 9 Control Statements 9.1 Introduction The normal flow of execution in a high level language is sequential, i.e., each statement is executed in the order of its appearance in the program. However, depending

More information

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

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June 2014. Dr.-Ing. Computers An Introduction to Programming with Python CCHSG Visit June 2014 Dr.-Ing. Norbert Völker Many computing devices are embedded Can you think of computers/ computing devices you may have in your

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 4: Conditional Execution These lecture notes are copyright (C) Marty Stepp and Stuart Reges, 2007. They may not be rehosted, sold, or modified without expressed permission

More information

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

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program. Name: Class: Date: Exam #1 - Prep True/False Indicate whether the statement is true or false. 1. Programming is the process of writing a computer program in a language that the computer can respond to

More information

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

Chapter 2: Algorithm Discovery and Design. Invitation to Computer Science, C++ Version, Third Edition Chapter 2: Algorithm Discovery and Design Invitation to Computer Science, C++ Version, Third Edition Objectives In this chapter, you will learn about: Representing algorithms Examples of algorithmic problem

More information

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

TIP: To access the WinRunner help system at any time, press the F1 key. CHAPTER 11 TEST SCRIPT LANGUAGE We will now look at the TSL language. You have already been exposed to this language at various points of this book. All the recorded scripts that WinRunner creates when

More information

Topic 11 Scanner object, conditional execution

Topic 11 Scanner object, conditional execution Topic 11 Scanner object, conditional execution "There are only two kinds of programming languages: those people always [complain] about and those nobody uses." Bjarne Stroustroup, creator of C++ Copyright

More information

Introduction to Java

Introduction to Java Introduction to Java The HelloWorld program Primitive data types Assignment and arithmetic operations User input Conditional statements Looping Arrays CSA0011 Matthew Xuereb 2008 1 Java Overview A high

More information

Interactive Applications (CLI) and Math

Interactive Applications (CLI) and Math Interactive Applications (CLI) and Math Interactive Applications Command Line Interfaces The Math Class Example: Solving Quadratic Equations Example: Factoring the Solution Reading for this class: L&L,

More information

6. Control Structures

6. Control Structures - 35 - Control Structures: 6. Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may bifurcate, repeat code or take decisions. For that purpose,

More information

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

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be... What is a Loop? CSC Intermediate Programming Looping A loop is a repetition control structure It causes a single statement or a group of statements to be executed repeatedly It uses a condition to control

More information

Chapter 4 Lecture Notes

Chapter 4 Lecture Notes Chapter 4 Lecture Notes Random Variables October 27, 2015 1 Section 4.1 Random Variables A random variable is typically a real-valued function defined on the sample space of some experiment. For instance,

More information

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

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void 1. Explain C tokens Tokens are basic building blocks of a C program. A token is the smallest element of a C program that is meaningful to the compiler. The C compiler recognizes the following kinds of

More information

Computer Programming I

Computer Programming I Computer Programming I Levels: 10-12 Units of Credit: 1.0 CIP Code: 11.0201 Core Code: 35-02-00-00-030 Prerequisites: Secondary Math I, Keyboarding Proficiency, Computer Literacy requirement (e.g. Exploring

More information

Random Fibonacci-type Sequences in Online Gambling

Random Fibonacci-type Sequences in Online Gambling Random Fibonacci-type Sequences in Online Gambling Adam Biello, CJ Cacciatore, Logan Thomas Department of Mathematics CSUMS Advisor: Alfa Heryudono Department of Mathematics University of Massachusetts

More information

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

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 Copyright c 2009 by Karl Sigman 1 Stopping Times 1.1 Stopping Times: Definition Given a stochastic process X = {X n : n 0}, a random time τ is a discrete random variable on the same probability space as

More information

Euler s Method and Functions

Euler s Method and Functions Chapter 3 Euler s Method and Functions The simplest method for approximately solving a differential equation is Euler s method. One starts with a particular initial value problem of the form dx dt = f(t,

More information

Two-way selection. Branching and Looping

Two-way selection. Branching and Looping Control Structures: are those statements that decide the order in which individual statements or instructions of a program are executed or evaluated. Control Structures are broadly classified into: 1.

More information

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

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system. http://www.tutorialspoint.com/java/java_quick_guide.htm JAVA - QUICK GUIDE Copyright tutorialspoint.com What is Java? Java is: Object Oriented Platform independent: Simple Secure Architectural- neutral

More information

Unit 6. Loop statements

Unit 6. Loop statements Unit 6 Loop statements Summary Repetition of statements The while statement Input loop Loop schemes The for statement The do statement Nested loops Flow control statements 6.1 Statements in Java Till now

More information

CS1010 Programming Methodology A beginning in problem solving in Computer Science. Aaron Tan http://www.comp.nus.edu.sg/~cs1010/ 20 July 2015

CS1010 Programming Methodology A beginning in problem solving in Computer Science. Aaron Tan http://www.comp.nus.edu.sg/~cs1010/ 20 July 2015 CS1010 Programming Methodology A beginning in problem solving in Computer Science Aaron Tan http://www.comp.nus.edu.sg/~cs1010/ 20 July 2015 Announcements This document is available on the CS1010 website

More information

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

IRA EXAMPLES. This topic has two examples showing the calculation of the future value an IRA (Individual Retirement Account). IRA EXAMPLES This topic has two examples showing the calculation of the future value an IRA (Individual Retirement Account). Definite Counting Loop Example IRA After x Years This first example illustrates

More information

Term Project: Roulette

Term Project: Roulette Term Project: Roulette DCY Student January 13, 2006 1. Introduction The roulette is a popular gambling game found in all major casinos. In contrast to many other gambling games such as black jack, poker,

More information

River Dell Regional School District. Computer Programming with Python Curriculum

River Dell Regional School District. Computer Programming with Python Curriculum River Dell Regional School District Computer Programming with Python Curriculum 2015 Mr. Patrick Fletcher Superintendent River Dell Regional Schools Ms. Lorraine Brooks Principal River Dell High School

More information

Sample CSE8A midterm Multiple Choice (circle one)

Sample CSE8A midterm Multiple Choice (circle one) Sample midterm Multiple Choice (circle one) (2 pts) Evaluate the following Boolean expressions and indicate whether short-circuiting happened during evaluation: Assume variables with the following names

More information

#820 Computer Programming 1A

#820 Computer Programming 1A Computer Programming I Levels: 10-12 Units of Credit: 1.0 CIP Code: 11.0201 Core Code: 35-02-00-00-030 Prerequisites: Secondary Math I, Keyboarding Proficiency, Computer Literacy requirement Semester 1

More information

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

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 BSc (Hons) in Computer Applications, BSc (Hons) Computer Science with Network Security, BSc (Hons) Business Information Systems & BSc (Hons) Software Engineering Cohort: BCA/07B/PT - BCA/06/PT - BCNS/06/FT

More information

Decision Making under Uncertainty

Decision Making under Uncertainty 6.825 Techniques in Artificial Intelligence Decision Making under Uncertainty How to make one decision in the face of uncertainty Lecture 19 1 In the next two lectures, we ll look at the question of how

More information

Computer Programming I

Computer Programming I Computer Programming I COP 2210 Syllabus Spring Semester 2012 Instructor: Greg Shaw Office: ECS 313 (Engineering and Computer Science Bldg) Office Hours: Tuesday: 2:50 4:50, 7:45 8:30 Thursday: 2:50 4:50,

More information

PHP Tutorial From beginner to master

PHP Tutorial From beginner to master PHP Tutorial From beginner to master PHP is a powerful tool for making dynamic and interactive Web pages. PHP is the widely-used, free, and efficient alternative to competitors such as Microsoft's ASP.

More information

Lecture Notes on Linear Search

Lecture Notes on Linear Search Lecture Notes on Linear Search 15-122: Principles of Imperative Computation Frank Pfenning Lecture 5 January 29, 2013 1 Introduction One of the fundamental and recurring problems in computer science is

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 4 Lecture 4-1: Scanner; if/else reading: 3.3 3.4, 4.1 Interactive Programs with Scanner reading: 3.3-3.4 1 Interactive programs We have written programs that print console

More information

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

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007 Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007 The Java Type System By now, you have seen a fair amount of Java. Time to study in more depth the foundations of the language,

More information

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

1. Then f has a relative maximum at x = c if f(c) f(x) for all values of x in some Section 3.1: First Derivative Test Definition. Let f be a function with domain D. 1. Then f has a relative maximum at x = c if f(c) f(x) for all values of x in some open interval containing c. The number

More information

Pseudo code Tutorial and Exercises Teacher s Version

Pseudo code Tutorial and Exercises Teacher s Version Pseudo code Tutorial and Exercises Teacher s Version Pseudo-code is an informal way to express the design of a computer program or an algorithm in 1.45. The aim is to get the idea quickly and also easy

More information

In this Chapter you ll learn:

In this Chapter you ll learn: Now go, write it before them in a table, and note it in a book. Isaiah 30:8 To go beyond is as wrong as to fall short. Confucius Begin at the beginning, and go on till you come to the end: then stop. Lewis

More information

While and Do-While Loops. 15-110 Summer 2010 Margaret Reid-Miller

While and Do-While Loops. 15-110 Summer 2010 Margaret Reid-Miller While and Do-While Loops 15-110 Margaret Reid-Miller Loops Within a method, we can alter the flow of control using either conditionals or loops. The loop statements while, do-while, and for allow us execute

More information

Stochastic Processes and Advanced Mathematical Finance. Ruin Probabilities

Stochastic Processes and Advanced Mathematical Finance. Ruin Probabilities Steven R. Dunbar Department of Mathematics 203 Avery Hall University of Nebraska-Lincoln Lincoln, NE 68588-0130 http://www.math.unl.edu Voice: 402-472-3731 Fax: 402-472-8466 Stochastic Processes and Advanced

More information

6. Standard Algorithms

6. Standard Algorithms 6. Standard Algorithms The algorithms we will examine perform Searching and Sorting. 6.1 Searching Algorithms Two algorithms will be studied. These are: 6.1.1. inear Search The inear Search The Binary

More information

Notes on Continuous Random Variables

Notes on Continuous Random Variables Notes on Continuous Random Variables Continuous random variables are random quantities that are measured on a continuous scale. They can usually take on any value over some interval, which distinguishes

More information

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 28, 2010 G. Lipari (Scuola Superiore Sant Anna) Introduction

More information

Lecture 13: Martingales

Lecture 13: Martingales Lecture 13: Martingales 1. Definition of a Martingale 1.1 Filtrations 1.2 Definition of a martingale and its basic properties 1.3 Sums of independent random variables and related models 1.4 Products of

More information

Computational Mathematics with Python

Computational Mathematics with Python Computational Mathematics with Python Basics Claus Führer, Jan Erik Solem, Olivier Verdier Spring 2010 Claus Führer, Jan Erik Solem, Olivier Verdier Computational Mathematics with Python Spring 2010 1

More information

JavaScript Introduction

JavaScript Introduction JavaScript Introduction JavaScript is the world's most popular programming language. It is the language for HTML, for the web, for servers, PCs, laptops, tablets, phones, and more. JavaScript is a Scripting

More information

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

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java CS1020 Data Structures and Algorithms I Lecture Note #1 Introduction to Java Objectives Java Basic Java features C Java Translate C programs in CS1010 into Java programs 2 References Chapter 1 Section

More information

CHM 579 Lab 1: Basic Monte Carlo Algorithm

CHM 579 Lab 1: Basic Monte Carlo Algorithm CHM 579 Lab 1: Basic Monte Carlo Algorithm Due 02/12/2014 The goal of this lab is to get familiar with a simple Monte Carlo program and to be able to compile and run it on a Linux server. Lab Procedure:

More information

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

Discrete Math in Computer Science Homework 7 Solutions (Max Points: 80) Discrete Math in Computer Science Homework 7 Solutions (Max Points: 80) CS 30, Winter 2016 by Prasad Jayanti 1. (10 points) Here is the famous Monty Hall Puzzle. Suppose you are on a game show, and you

More information

AMS 5 CHANCE VARIABILITY

AMS 5 CHANCE VARIABILITY AMS 5 CHANCE VARIABILITY The Law of Averages When tossing a fair coin the chances of tails and heads are the same: 50% and 50%. So if the coin is tossed a large number of times, the number of heads and

More information

Exercise 4 Learning Python language fundamentals

Exercise 4 Learning Python language fundamentals Exercise 4 Learning Python language fundamentals Work with numbers Python can be used as a powerful calculator. Practicing math calculations in Python will help you not only perform these tasks, but also

More information

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

Sources: On the Web: Slides will be available on: C programming Introduction The basics of algorithms Structure of a C code, compilation step Constant, variable type, variable scope Expression and operators: assignment, arithmetic operators, comparison,

More information

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

Overview. java.math.biginteger, java.math.bigdecimal. Definition: objects are everything but primitives The eight primitive data type in Java Data Types The objects about which computer programs compute is data. We often think first of integers. Underneath it all, the primary unit of data a machine has is a chunks of bits the size of a word.

More information

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

Wald s Identity. by Jeffery Hein. Dartmouth College, Math 100 Wald s Identity by Jeffery Hein Dartmouth College, Math 100 1. Introduction Given random variables X 1, X 2, X 3,... with common finite mean and a stopping rule τ which may depend upon the given sequence,

More information

Introduction to Matrices

Introduction to Matrices Introduction to Matrices Tom Davis tomrdavis@earthlinknet 1 Definitions A matrix (plural: matrices) is simply a rectangular array of things For now, we ll assume the things are numbers, but as you go on

More information

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

Some programming experience in a high-level structured programming language is recommended. Python Programming Course Description This course is an introduction to the Python programming language. Programming techniques covered by this course include modularity, abstraction, top-down design,

More information

Chapter 8 Selection 8-1

Chapter 8 Selection 8-1 Chapter 8 Selection 8-1 Selection (Decision) The second control logic structure is selection: Selection Choosing between two or more alternative actions. Selection statements alter the sequential flow

More information

MTH6120 Further Topics in Mathematical Finance Lesson 2

MTH6120 Further Topics in Mathematical Finance Lesson 2 MTH6120 Further Topics in Mathematical Finance Lesson 2 Contents 1.2.3 Non-constant interest rates....................... 15 1.3 Arbitrage and Black-Scholes Theory....................... 16 1.3.1 Informal

More information

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

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C Embedded Systems A Review of ANSI C and Considerations for Embedded C Programming Dr. Jeff Jackson Lecture 2-1 Review of ANSI C Topics Basic features of C C fundamentals Basic data types Expressions Selection

More information

While Loop. 6. Iteration

While Loop. 6. Iteration While Loop 1 Loop - a control structure that causes a set of statements to be executed repeatedly, (reiterated). While statement - most versatile type of loop in C++ false while boolean expression true

More information

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.

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. LING115 Lecture Note Session #4 Python (1) 1. Introduction As we have seen in previous sessions, we can use Linux shell commands to do simple text processing. We now know, for example, how to count words.

More information

Introduction to Python

Introduction to Python Caltech/LEAD Summer 2012 Computer Science Lecture 2: July 10, 2012 Introduction to Python The Python shell Outline Python as a calculator Arithmetic expressions Operator precedence Variables and assignment

More information

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

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

More information

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

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0 VISUAL GUIDE to RX Scripting for Roulette Xtreme - System Designer 2.0 UX Software - 2009 TABLE OF CONTENTS INTRODUCTION... ii What is this book about?... iii How to use this book... iii Time to start...

More information

Computational Mathematics with Python

Computational Mathematics with Python Boolean Arrays Classes Computational Mathematics with Python Basics Olivier Verdier and Claus Führer 2009-03-24 Olivier Verdier and Claus Führer Computational Mathematics with Python 2009-03-24 1 / 40

More information

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

Software Development. Chapter 7. Outline. 7.1.1 The Waterfall Model RISKS. Java By Abstraction Chapter 7 Outline Chapter 7 Software Development 7.1 The Development Process 7.1.1 The Waterfall Model 7.1.2 The Iterative Methodology 7.1.3 Elements of UML 7.2 Software Testing 7.2.1 The Essence of Testing 7.2.2

More information

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

1.00/1.001 - Session 2 Fall 2004. Basic Java Data Types, Control Structures. Java Data Types. 8 primitive or built-in data types 1.00/1.001 - Session 2 Fall 2004 Basic Java Data Types, Control Structures Java Data Types 8 primitive or built-in data types 4 integer types (byte, short, int, long) 2 floating point types (float, double)

More information

Quosal Form Designer Training Documentation

Quosal Form Designer Training Documentation Chapter 4 Advanced Form Design Concepts There is a huge amount of customization that can be done with the Report Designer, and basic quote forms only scratch the surface. Learning how to use the advanced

More information

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

API for java.util.iterator. ! hasnext() Are there more items in the list? ! next() Return the next item in the list. Sequences and Urns 2.7 Lists and Iterators Sequence. Ordered collection of items. Key operations. Insert an item, iterate over the items. Design challenge. Support iteration by client, without revealing

More information

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

Now is the time. For all good men PERMUTATION GENERATION. Princeton University. Robert Sedgewick METHODS Now is the time For all good men PERMUTATION GENERATION METHODS To come to the aid Of their party Robert Sedgewick Princeton University Motivation PROBLEM Generate all N! permutations of N elements Q:

More information

Binary Number System. 16. Binary Numbers. Base 10 digits: 0 1 2 3 4 5 6 7 8 9. Base 2 digits: 0 1

Binary Number System. 16. Binary Numbers. Base 10 digits: 0 1 2 3 4 5 6 7 8 9. Base 2 digits: 0 1 Binary Number System 1 Base 10 digits: 0 1 2 3 4 5 6 7 8 9 Base 2 digits: 0 1 Recall that in base 10, the digits of a number are just coefficients of powers of the base (10): 417 = 4 * 10 2 + 1 * 10 1

More information

Arrays. Introduction. Chapter 7

Arrays. Introduction. Chapter 7 CH07 p375-436 1/30/07 1:02 PM Page 375 Chapter 7 Arrays Introduction The sequential nature of files severely limits the number of interesting things you can easily do with them.the algorithms we have examined

More information

Programming Database lectures for mathema

Programming Database lectures for mathema Programming Database lectures for mathematics students April 25, 2015 Functions Functions are defined in Postgres with CREATE FUNCTION name(parameter type,...) RETURNS result-type AS $$ function-body $$

More information

2.3 WINDOW-TO-VIEWPORT COORDINATE TRANSFORMATION

2.3 WINDOW-TO-VIEWPORT COORDINATE TRANSFORMATION 2.3 WINDOW-TO-VIEWPORT COORDINATE TRANSFORMATION A world-coordinate area selected for display is called a window. An area on a display device to which a window is mapped is called a viewport. The window

More information

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

Stochastic Processes and Advanced Mathematical Finance. Duration of the Gambler s Ruin Steven R. Dunbar Department of Mathematics 203 Avery Hall University of Nebraska-Lincoln Lincoln, NE 68588-0130 http://www.math.unl.edu Voice: 402-472-3731 Fax: 402-472-8466 Stochastic Processes and Advanced

More information

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

1. Overconfidence {health care discussion at JD s} 2. Biased Judgments. 3. Herding. 4. Loss Aversion In conditions of laissez-faire the avoidance of wide fluctuations in employment may, therefore, prove impossible without a far-reaching change in the psychology of investment markets such as there is no

More information

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

SOME ASPECTS OF GAMBLING WITH THE KELLY CRITERION. School of Mathematical Sciences. Monash University, Clayton, Victoria, Australia 3168 SOME ASPECTS OF GAMBLING WITH THE KELLY CRITERION Ravi PHATARFOD School of Mathematical Sciences Monash University, Clayton, Victoria, Australia 3168 In this paper we consider the problem of gambling with

More information

Expected Value and the Game of Craps

Expected Value and the Game of Craps Expected Value and the Game of Craps Blake Thornton Craps is a gambling game found in most casinos based on rolling two six sided dice. Most players who walk into a casino and try to play craps for the

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 5 Lecture 5-2: Random Numbers reading: 5.1-5.2 self-check: #8-17 exercises: #3-6, 10, 12 videos: Ch. 5 #1-2 1 The Random class A Random object generates pseudo-random* numbers.

More information