Data types, assignment statements, and math functions allow you to compute You write a sequence of statements that tell the computer what needs to be done.

Slides:



Advertisements
Similar presentations
Week 5: Loops 1.  Repetition is the ability to do something over and over again  With repetition in the mix, we can solve practically any problem that.
Advertisements

Computer Science A 4 13/3. Goals To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To understand.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Loops Repeat after me …. Loops A loop is a control structure in which a statement or set of statements execute repeatedly How many times the statements.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
1.3 Conditionals and Loops Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008 · October.
Chapter 6: Iteration Part 1. To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To understand.
CSC 204 Programming I Loop I The while statement.
Flow Control in Java. Controlling which instruction to execute next Sequential  Similar to walking, one step after another Branching  Similar to a fork.
Chapter 5 Loops.
 Executes a block of code repeatedly  A condition controls how often the loop is executed  Most commonly, the statement is a block statement (set of.
Computer Science Department LOOPS. Computer Science Department Loops Loops Cause a section of your program to be repeated a certain number of times. The.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Flow Control in Java. Controlling which instruction to execute next Sequential  Similar to walking, one step after another Branching  Similar to a fork.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Chapter 4: Control Structures II
Chapter 5: Control Structures II
Recap of Functions. Functions in Java f x y z f (x, y, z) Input Output Algorithm Allows you to clearly separate the tasks in a program. Enables reuse.
Conditional Loops CSIS 1595: Fundamentals of Programming and Problem Solving 1.
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
Decisions, Decisions, Decisions Conditional Statements In Java.
1.3 Conditionals and Loops Copyright 2004, FoxTrot by Bill Amend
The for loop.
CompSci 100e2.1 1 N-Body Simulation l Applications to astrophysics.  Orbits of solar system bodies.  Stellar dynamics at the galactic center.  Stellar.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
Computer Programming 12 Lesson 6 – Loop structure By: Dan Lunney.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
Lesson 7 Iteration Structures. Iteration is the third control structure we will explore. Iteration simply means to do something repeatedly. All iteration.
CS 106 Introduction to Computer Science I 02 / 15 / 2008 Instructor: Michael Eckmann.
Session Three Review & Conditional Control Flow. Java File Hierarchy Projects Packages Classes Methods.
Sophomore Scholars Java
Lecture 4b Repeating With Loops
REPETITION CONTROL STRUCTURE
Repetition (While-Loop) version]
ECS10 10/10
Chapter 6 More Conditionals and Loops
Chapter 5: Control Structures II
The order in which statements are executed is called the flow of control. Most of the time, a running program starts at the first programming statement,
User input We’ve seen how to use the standard output buffer
Repetition-Counter control Loop
Selected Topics From Chapter 6 Iteration
Flow Control in Java.
Chapter 4 LOOPS © Bobby Hoggard, Department of Computer Science, East Carolina University / These slides may not be used or duplicated without permission.
A Balanced Introduction to Computer Science David Reed, Creighton University ©2005 Pearson Prentice Hall ISBN X Chapter 13 (Reed) - Conditional.
Looping and Repetition
Iteration with While You can say that again.
Outline Altering flow of control Boolean expressions
LRobot Game.
Chapter 6: Repetition Structures
Chapter 5: Repetition Structures
Java Programming Loops
Outline Boolean Expressions The if Statement Comparing Data
Loops CIS 40 – Introduction to Programming in Python
Loop Strategies Repetition Playbook.
Computer programming Lecture 3.
OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS
Repetition Statements (Loops) - 2
Repetition Statements
Introduction to Computer Science I.
CSC 1051 – Data Structures and Algorithms I
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
Conditionals and Loops
Chapter 13 Conditional Repetition
A Balanced Introduction to Computer Science David Reed, Creighton University ©2005 Pearson Prentice Hall ISBN X Chapter 13 (Reed) - Conditional.
Repetition CSC 1051 – Data Structures and Algorithms I Course website:
Looping and Repetition
Presentation transcript:

Data types, assignment statements, and math functions allow you to compute You write a sequence of statements that tell the computer what needs to be done. Issues: Some computations make sense only under certain conditions at occur when the program is running. The computations may need to be done repeatedly to solve a big problem. statement 1 statement 2 statement 3 statement 4

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

Control Flow Control flow. Sequence of statements that are actually executed in a program. Conditionals and loops: enable us to choreograph control flow. boolean 1 straight-line control flow statement 2 statement 1 statement 4 statement 3 straight-line programs: akin to calculator true false statement 1 boolean 2 true statement 2 false statement 3 control flow with conditionals and loops

Conditionals

If Statement The if statement. A common branching structure. Check boolean condition. If true, execute some statements. If false, execute other statements. if (boolean expression) { statement T; } else { statement F; boolean expression can be any sequence of statements true false statement T statement F

If Statement The if statement. A common branching structure. Check boolean condition. If true, execute some statements. If false, execute other statements. Notice no curly braces Again no curly braces

If Statement Example – Flipping a Coin 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"); elseMath.random() < 0.5) System.out.println("Tails"); }

The While Loop

While Loop The while loop. A common repetition structure. Check a boolean expression. Execute a sequence of statements. Repeat. loop continuation condition straight-line program: amount of data processed proportional to number of lines of codes written, even with conditionals loops: brings you to infinite statement 2 while (boolean expression) { statement 1; statement 2; } loop body boolean expression true statement 1 false

While Loops: Powers of Two Ex. Print first n powers of 2. Increment i from 1 to n. Double v each time. int i = 0; int v = 1; while (i <= n) { System.out.println(v); i = i + 1; v = 2 * v; } Note: assignment is not mathematical equality. Curly braces delimit a block – unlike before, curly braces are needed since block has three statements. n = 6

While Loops: Powers of Two Ex. Print first n powers of 2. Increment i from 1 to n. Double v each time. i % java Powers int i = 0; int v = 1; while (i <= n) { System.out.println(v); i = i + 1; v = 2 * v; } n = 6

While Loops: Powers of Two Ex. Print first n powers of 2. Increment i from 1 to n. Double v each time. i v 1 % java Powers int i = 0; int v = 1; while (i <= n) { System.out.println(v); i = i + 1; v = 2 * v; } n = 6

While Loops: Powers of Two Ex. Print first n powers of 2. Increment i from 1 to n. Double v each time. i v i <= n 1 true % java Powers int i = 0; int v = 1; while (i <= n) { System.out.println(v); i = i + 1; v = 2 * v; } n = 6

While Loops: Powers of Two Ex. Print first n powers of 2. Increment i from 1 to n. Double v each time. i v i <= n 1 true % java Powers 1 int i = 0; int v = 1; while (i <= n) { System.out.println(v); i = i + 1; v = 2 * v; } n = 6

While Loops: Powers of Two Ex. Print first n powers of 2. Increment i from 1 to n. Double v each time. i v i <= n 1 true % java Powers 1 int i = 0; int v = 1; while (i <= n) { System.out.println(v); i = i + 1; v = 2 * v; } 1 n = 6

While Loops: Powers of Two Ex. Print first n powers of 2. Increment i from 1 to n. Double v each time. i v i <= n 1 true % java Powers 1 int i = 0; int v = 1; while (i <= n) { System.out.println(v); i = i + 1; v = 2 * v; } 1 2 n = 6

While Loops: Powers of Two Ex. Print first n powers of 2. Increment i from 1 to n. Double v each time. i v i <= n 1 true % java Powers 1 int i = 0; int v = 1; while (i <= n) { System.out.println(v); i = i + 1; v = 2 * v; } 1 2 true n = 6

While Loops: Powers of Two Ex. Print first n powers of 2. Increment i from 1 to n. Double v each time. i v i <= n 1 true % java Powers 1 2 int i = 0; int v = 1; while (i <= n) { System.out.println(v); i = i + 1; v = 2 * v; } 1 2 true n = 6

While Loops: Powers of Two Ex. Print first n powers of 2. Increment i from 1 to n. Double v each time. i v i <= n 1 true % java Powers 1 2 int i = 0; int v = 1; while (i <= n) { System.out.println(v); i = i + 1; v = 2 * v; } 1 2 true 2 n = 6

While Loops: Powers of Two Ex. Print first n powers of 2. Increment i from 1 to n. Double v each time. i v i <= n 1 true % java Powers 1 2 int i = 0; int v = 1; while (i <= n) { System.out.println(v); i = i + 1; v = 2 * v; } 1 2 true 2 4 n = 6

While Loops: Powers of Two Ex. Print first n powers of 2. Increment i from 1 to n. Double v each time. i v i <= n 1 true % java Powers 1 2 int i = 0; int v = 1; while (i <= n) { System.out.println(v); i = i + 1; v = 2 * v; } 1 2 true 2 4 true n = 6

While Loops: Powers of Two (Final State) Ex. Print first n powers of 2. Increment i from 1 to n. Double v each time. i v i <= N 1 true % java Powers 1 2 4 8 16 32 64 int i = 0; int v = 1; while (i <= N) { System.out.println(v); i = i + 1; v = 2 * v; } 1 2 true 2 4 true Note: assignment is not mathematical equality. 3 8 true 4 16 true 5 32 true 6 64 true 7 128 false n = 6

Anything wrong with the following code for printing powers of 2? Question 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; YES. Need braces around statements in while loop. Indentation does not imply braces!Without braces, program enters an infinite loop printing 1s. Beginning programmer's first moment of panic: how to stop it?

Q. Anything wrong with the following code for printing powers of 2? While Loop Question Q. Anything wrong with the following code for printing powers of 2? A. Need curly braces around statements in while loop; otherwise it enters an infinite loop, printing 1s. int i = 0; int v = 1; while (i <= N) System.out.println(v); i = i + 1; v = 2 * v; Indentation does not imply braces! Tools -> Reset Interactions in DrJava Ctrl-c from command line

The For Loop

For Loops The for loop. Another common repetition structure. Execute initialization statement. Check boolean expression. Execute sequence of statements. Execute increment statement. Repeat. loop continuation condition init Compact notation for common looping scheme. increment for (init; boolean expression; increment) { statement 1; statement 2; } statement 2 body boolean expression true statement 1 false

Powers of Two Code using While Loop Code using For Loop int i = 0; int v = 1; while (i <= N) { System.out.println(v); i = i + 1; v = 2 * v; } int v = 1; for (int i = 0; i <= N; i++) { System.out.println(v); v = 2 * v; } Code using While Loop Code using For Loop

Recap - Conditionals and Loops Conditionals enable you to do one of 2n sequences of operations with n lines. Loops enable you to do an operation n times using only 2 lines of code. if (a0 > 0) System.out.print(0); if (a1 > 0) System.out.print(1); if (a2 > 0) System.out.print(2); if (a3 > 0) System.out.print(3); if (a4 > 0) System.out.print(4); if (a5 > 0) System.out.print(5); if (a6 > 0) System.out.print(6); if (a7 > 0) System.out.print(7); if (a8 > 0) System.out.print(8); if (a9 > 0) System.out.print(9); double sum = 0.0; for (int i = 1; i <= 1024; i++) sum = sum + 1.0 / i; computes 1/1 + 1/2 + ... + 1/1024 Nth harmonic number is approximately ln(n) + 0.57721.... 210 = 1024 possible results, depending on input

Calculating Graduated Income Tax (Group Activity) Pay a certain tax rate depending on income level. Income Rate 0 - 47,450 22% 47,450 – 114,650 25% 114,650 – 174,700 28% IS THIS CODE CORRECT? WHAT IS WRONG WITH IT? HOW SHOULD WE REALLY CALCULATE IT? 174,700 – 311,950 33% 311,950 - 35% 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; IS THIS CODE CORRECT?

Nesting

Nested If Statements Ex. Pay a certain tax rate depending on income level. Income Rate 0 - 47,450 22% 47,450 – 114,650 25% 5 mutually exclusive alternatives 114,650 – 174,700 28% nested conditionals: this is actually 4 different if-else statements, but no need for braces 174,700 – 311,950 33% 311,950 - 35% double rate; 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 if (income < 311950) rate = 0.35; graduated income tax calculation

Nesting Conditionals and Loops Nest conditionals within conditionals. Nest loops within loops. Nest conditionals within loops within loops.

Putting it All Together: Monte Carlo Simulation

Monte Carlo Simulation Developed in the 1940s by physicists at Los Alamos National Lab For modeling phenomena with significant uncertainty in the inputs Uses random sampling to compute the results

Steps in a Monte Carlo Simulation Define a domain of possible inputs. Generate inputs randomly from the domain. Perform a deterministic computation using the inputs. Aggregate the results of the individual computations into the final result.

Gambler's Ruin 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? Monte Carlo simulation. Flip digital coins and see what happens. Repeat and compute statistics. discrete analog of Brownian motion (applications to stock market – Black-Scholes, behavior of atomic particles predicted by quantum physics, dispersion of ink flowing in water) Simulations of this sort are widely used in economics, science and engineering

Gambler's Ruin public class Gambler { public static void main(String[] args) { int stake = Integer.parseInt(args[0]); int goal = Integer.parseInt(args[1]); int trials = Integer.parseInt(args[2]); int wins = 0; System.out.println(wins + " wins of " + trials); } // repeat experiment N times for (int i = 0; i < trials; i++) { } // do one gambler's ruin experiment int t = stake; while (t > 0 && t < goal) { } if (t == goal) wins++; This program is worthy of careful study. Conditional within a while loop within a for loop. Inner loop uses && to continue as long as gambler is not broke and didn't reach goal // flip coin and update if (Math.random() < 0.5) t++; else t--;

Digression: Simulation and Analysis Fact. Probability of winning = stake  goal. Fact. Expected number of bets = stake  desired gain. Ex. 20% chance of turning $500 into $2500, but expect to make one million $1 bets. Remark. Both facts can be proved mathematically; for more complex scenarios, computer simulation is often the best plan of attack. stake goal trials % java Gambler 5 25 1000 191 wins of 1000 203 wins of 1000 % java Gambler 500 2500 1000 197 wins of 1000 after a substantial wait…. substantial wait = hours 500/2500 = 20% 500 * (2500 - 500) = 1 million