Code Compression the benefits of looping... Today in CS 5 HW 4 - (3 problems) M/T sections W/Th sections due Sunday, 9/26 at midnight due Monday, 9/27.

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

The if-else Statements
Programing Concept Ken Youssefi/Ping HsuIntroduction to Engineering – E10 1 ENGR 10 Introduction to Engineering (Part A)
CS 106 Introduction to Computer Science I 02 / 18 / 2008 Instructor: Michael Eckmann.
Computer Science 1620 Loops.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
COMP 14 Introduction to Programming Mr. Joshua Stough February 16, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
 Monday, 9/30/02, Slide #1 CS106 Introduction to CS1 Monday, 9/30/02  QUESTIONS (on HW02, etc.)??  Today: Libraries, program design  More on Functions!
Loops – While, Do, For Repetition Statements Introduction to Arrays
1 CS 177 Week 15 Recitation Slides Review. Announcements Final Exam on Sat. May 8th  PHY 112 from 8-10 AM Complete your online review of your classes.
CS 106 Introduction to Computer Science I 10 / 04 / 2006 Instructor: Michael Eckmann.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Homework 4 Due ( MT sections ) ( WTh sections ) at midnight Sun., 9/29 Mon., 9/30 Problems
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
CS 106 Introduction to Computer Science I 09 / 28 / 2007 Instructor: Michael Eckmann.
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
Introduction to Programming G51PRG University of Nottingham Revision 2 Essam Eliwa.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
COMP More About Classes Yi Hong May 22, 2015.
Lecture 10 Instructor: Craig Duckett. Assignment 2 Revision TONIGHT DUE TONIGHT Wednesday, August 5 th Assignment 3 NEXT DUE NEXT Monday, August 10 th.
Arrays (Part 1) Computer Science Erwin High School Fall 2014.
Introduction to Java Thanks to Dan Lunney (SHS). Java Basics File names The “main” method Output to screen Escape Sequence – Special Characters format()
Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements.
CSC204 – Programming I Lecture 4 August 28, 2002.
Selection (if-then-else) Programming Has 3 Types of Control: Sequential (normal): Control of Execution Proceeds One after the Other Selection (if-then-else):
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 5: Software Design & Testing; Revision Session.
EPSII 59:006 Spring Introduction to C More Administrative Details The C Programming Language How a computer processes programs Your first C program.
Homework 3 Due ( MT sections ) ( WTh sections ) at midnight Sun., 9/21 Mon., 9/22 Problems
This week in CS 5 HW 9 (2 problems) M/T sections W/Th sections due Sunday, 11/4 at midnight due Monday, 11/5 at midnight Recitation for HW9 -- Friday 11/2.
Variables and Functions. Open your Encoder program Let’s begin by opening the “Labyrinth Auto Straight” code. Save this file as Labyrinth with variables.
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.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Methods (a.k.a. Functions)
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
Current Assignments Homework 2 is available and is due in three days (June 19th). Project 1 due in 6 days (June 23 rd ) Write a binomial root solver using.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.
More on Logic Today we look at the for loop and then put all of this together to look at some more complex forms of logic that a program will need The.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
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.
Week 3 - Wednesday.  What did we talk about last time?  Other C features  sizeof, const  ASCII table  printf() format strings  Bitwise operations.
Chapter 4: Control Structures II
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
1 Loops II. 2 Recall the while Loop int sum = 0; int i = 1;... /* Sum the integers 1 to 10 */ while ( i
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Java methods Methods break down large problems into smaller ones Your program may call the same method many times saves writing and maintaining same code.
More loops while and do-while. Recall the for loop in general for (initialization; boolean_expression; update) { }
Homework 8 Due ( MT sections ) ( WTh sections ) at midnight Sun., 10/28 Mon., 10/29 Problems Reading is under week 7, however.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
The for loop.
EECS 110: Lec 7: Program Planning Aleksandar Kuzmanovic Northwestern University
1 Project 7: Looping. Project 7 For this project you will produce two Java programs. The requirements for each program will be described separately on.
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.
Week 3 - Friday.  What did we talk about last time?  Preprocessor directives  Other C features  sizeof, const  ASCII table  printf() format strings.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Lecture 4b Repeating With Loops
REPETITION CONTROL STRUCTURE
CS 106A, Lecture 6 Control Flow and Parameters
Chapter 4 LOOPS © Bobby Hoggard, Department of Computer Science, East Carolina University / These slides may not be used or duplicated without permission.
Lecture 5: For Loops Building Java Programs: A Back to Basics Approach
Week 4 Lecture-2 Chapter 6 (Methods).
OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS
Java LESSON 3 Loops.
Unit 3: Variables in Java
Loops CGS3416 Spring 2019 Lecture 7.
While Loops in Python.
Presentation transcript:

Code Compression the benefits of looping... Today in CS 5 HW 4 - (3 problems) M/T sections W/Th sections due Sunday, 9/26 at midnight due Monday, 9/27 at midnight Reading: Class notes for week 4 Coding style & commenting will count for HW4 ! Let’s Make a Deal Friday, 8:00 am – recitation section Grading and the submission website... concerns? questions? optional, but all are welcome! Lab: N-Z all others welcome!

Today in CS 5 Code Compression the benefits of looping... int i = 0; while (i < 4) { ++i; } for (int i=0 ; i<4 ; ++i) { ; } for loop while loop more braces!

Style /* * Author: me! * Date: 9/26/04 * Time: d+(int)d/x minutes * Comment: The virtual lyricist */ class CS5App { public static void main(String[] args) { H.pl(“Enter your favorite mascot: ”); String mascot = H.nw(); … more code here … } leave space before blocks of code leave space between parts of code that do different things introductory comment indent code evenly within the surrounding braces align curly braces that correspond use reasonable variable names

Comments ? /* * Author: me! * Date: 9/26/04 * Time: 3 kiloseconds * Comment: Finding the max and min of 4 values */ if ( a < b && a < c && a < d ) // see if a is minimal { H.pl(“ Minimum is ” + a); } else if ( b < a && b < c && b < d ) // see if b is minimal { H.pl(“ Minimum is ” + b); } introductory comment comment at least each block of code very small blocks need only one comment for the entire group

Back inside the machine... Shortcuts for changing variables: i++;++i; int i = 35; i = i + 1; i += 1;

Back inside the machine... Shortcuts for changing variables: i++;++i; int i = 35; i = i + 1; i += 1; all of these increment i by 1

Back inside the machine... Shortcuts for changing variables: i++;++i; int i = 35; i = i + 1; i += 1; int amoebas = ; amoebas = amoebas * 2; double hwToGo = 11.0; hwToGo = hwToGo - 1; long u235 = L; u235 = u235 / 2; all of these increment i by 1

Back inside the machine... Shortcuts for changing variables: i++;++i; int i = 35; i = i + 1; i += 1; int amoebas = ; amoebas = amoebas * 2; double hwToGo = 11.0; hwToGo = hwToGo - 1; long u235 = L; u235 = u235 / 2; all of these increment i by 1 amoebas *= 2; hwToGo -= 1;--hwToGo; u235 /= 2;

An aside What’s the difference between i++++i and? Nothing -- when they are on their own!

An aside What’s the difference between i++++i and? Nothing -- when they are on their own! When they are being used and set at the same time things change... int i = 32; int x = ++i + 10; int i = 32; int x = i ; increments after useincrements before use

An aside What’s the difference between i++++i and? Nothing -- when they are on their own! When they are being used and set at the same time things change... int i = 32; int x = ++i + 10; int i = 32; int x = i ; increments after useincrements before use i is 33 x is 43 i is 33 x is 42

Hw 4, Problem 1 Hw4Pr1) The improved math menu... Option # 2: this integral Option # 4: unlimited max and min Hw4Pr2) Let’s Make a Deal ! Hw4Pr3) Let’s Make A LOT of Deals. Option # 3: function graphing Option # 0: sequences Option # 1: raw power dx x = 0 x =  the period of a pendulum with length L and initial angle a Pair Programming Problem

code != work Sequencing items with a single piece of code

code != work Sequencing items with a single piece of code

Anatomy of a for loop for ( int i = 0 ; i < 4 ; ++i ) { H.pl(i); }

Anatomy of a for loop for ( int i = 0 ; i < 4 ; ++i ) { H.pl(i); } PART 1PART 2 PART 3 PART 4

Anatomy of a for loop for ( int i = 0 ; i < 4 ; ++i ) { H.pl(i); } PART 1PART 2 PART 1 PART 4 int i 0 PART 2 PART 3 PART 4 create and initialize loop variable PART 3 test to determine if we run the loop loop body is run if test is true update the loop variable always truefalse i<4 end loop

code != work Sequencing items with a single piece of code

an egocentric for loop for ( int i = 1 ; i <= 6 ; ++i ) { H.p( 7*i ); }

a selfless for loop int x = 42; for ( int i = 0 ; i < 6 ; ++i ) { H.p( x + “ ” ); }

sharing with if int x = 3; for ( int i = 0 ; i < 6 ; ++i ) { H.p( x + “ ” ); if (x%2 == 0) else }

“Quiz” Print the output of these loops A B C int s = 0; for (int i = 1 ; i < 5 ; ++i) { H.p( i + “ ” ); s = s + i; } H.pl(“\ns is ” + s); int c = 0; for (int i=10 ; i>0 ; i/=2 ) { H.p( i + “ ” ); c++; } H.pl(“c is ” + c); for (int i = 0 ; i != 4 ; i+=1) { H.p( i + “ ” ); } “Extra Credit” change one character in the code above so that this loop runs times.

“Quiz”, part Write a loop to print this sequence: 9 terms total terms total Write a loop to print this sequence: Hint: Use a for loop with an if inside it! Hint: Use a for loop with a for loop inside it!

Variables: a life story... int sum = 0; for ( int i = 1 ; i < 5 ; ++i ) { sum = sum + i; } H.pl(“sum is ” + sum); int sum = 0; for ( int i = 0 … Why will java complain about this ?!?

Variables: a life story... int sum = 0; for ( int i = 1 ; i < 5 ; ++i ) { sum = sum + i; } H.pl(“sum is ” + sum); int sum = 0; for ( int i = 0 … (1) Birth (of sum and i ) Why will java complain about this ?!?

Variables: a life story... int sum = 0; for ( int i = 1 ; i < 5 ; ++i ) { sum = sum + i; } H.pl(“sum is ” + sum); int sum = 0; for ( int i = 0 … (1) Birth (of sum and i ) (2) Growth Why will java complain about this ?!?

Variables: a life story... int sum = 0; for ( int i = 1 ; i < 5 ; ++i ) { sum = sum + i; } H.pl(“sum is ” + sum); int sum = 0; for ( int i = 0 … (1) Birth (of sum and i ) (2) Growth (3) Death (of i ) but sum lives on… Why will java complain about this ?!?

Variables: a life story... int sum = 0; for ( int i = 1 ; i < 5 ; ++i ) { sum = sum + i; } H.pl(“sum is ” + sum); sum = 0; for ( int i = 0 … (1) Birth (of sum and i ) (2) Growth (3) Death (of i ) but sum lives on… reuse is OK recreation is not!

What’s this all for ? Program for finding the factorial of a number… H.pl(“Type an integer n and I will print n!”); int n = H.ni(); // we have n – we need n factorial int result = ; // be sure to give an initial value H.pl(“The result is ” + result); Use the same idea for creating powers in Hw4 Pr1 !

Perspective on for loops // Name: CS5App // Author: Matt Beaumont // Purpose: To get me out of CS5... //...no, really... // Purpose: To create and maintain a list // of films and directors /* Notes: * I haven't liked for-loops since the day I met them. * They bother me for some reason. Hence, no for-loops… */ class CS5App {... At the top of a CS 5 placement project file …

Extreme Looping Java’s last and least built-in variable type: boolean H.pl(“It keeps on”); while ( true ) { H.pl(“going and”); } “while” block

Extreme Looping Java’s last and least built-in variable type: boolean H.pl(“It keeps on”); while ( true ) { H.pl(“going and”); } “while” block note what’s NOT here!

Extreme Looping with while No variable or expression is needed! H.pl(“It keeps on”); while ( true ) { H.pl(“going and”); int escape = H.randInt(1,100); if (escape == 100) { break; } worry later about how to escape ! here is how to quit – use break !

“User – friendly” code long myNumber = H.randLong(0, L); while ( true ) { H.pl(“I’m thinking of a positive integer”); H.pl(“If you guess it, you may leave.”); H.pl(“Otherwise, you must continue…\n”); H.p(“What is your guess? ”); int yourGuess = H.ni(); if ( yourGuess == myNumber ) { break; // let me out ! } A break breaks out of the enclosing switch, for, or while.

“User – friendly” code long myNumber = H.randLong(0, L); while ( true ) { H.pl(“I’m thinking of a positive integer”); H.pl(“If you guess it, you may leave.”); H.pl(“Otherwise, you must continue…\n”); H.p(“What is your guess? ”); int yourGuess = H.ni(); if ( yourGuess == myNumber ) break; // let me out ! H.p(“Would you like to continue playing? ”); String answer = H.nl(); if (answer == “no”) break; } but friendlier! same as before

Monty Hall Let’s make a deal ’63-’86 Sept inspiring the “Monty Hall paradox” Hw4Pr2) The Virtual Monty Hall

The two Monte Carlos Monte Carlo casino, Monaco Making random numbers work for you! Monte Carlo methods, Math/CS math hw cs hw physics hw Hum hw

Monte Carlo Monty Hall Suppose you always switch to the other door... What are the chances that you will win the car ? Hw4Pr3) Monte Carlo Monty Hall Run it (randomly) 1000 times and see!

Monty Hall program design top-down software engineering while (true) // program skeleton via short comments { } HW4PR3) Virtual Monty Hall Detailed design this Friday in recitation…

Monte Carlo in action Suppose you roll two dice. What are the chances that you roll doubles? int doublesCount = 0; for (int i=0 ; i<1000 ; ++i) { int d1 = H.randInt(1,6); int d2 = H.randInt(1,6); if ( d1 == d2 ) { ++doublesCount; } H.pl(“We rolled ” + doublesCount + “ doubles.”); one roll of the dice 1000 times count the number of doubles rolled set up a variable to count the number of doubles rolled

Summary for loop examples while loop examples statements and shortcuts for changing variables for (int i=12 ; i>=0 ; i-=2) { H.p( i + “ ” ); } int x = 3; for (int i=0 ; i<9 ; ++i) { H.p( x + “ ” ); x = x + 12; } x *= 10; num += 10; while ( true ) { String s = H.nw(); if (s.equals(“no”)) break; } ++i; i++;--i; i--; multiply x by 10increase num by 10increase i by 1decrease i by 1 prints prints continues until the user types “no”

Lab Today I’d suggest starting by writing the for loops in Hw4Pr1 then move on to the more involved examples use loops to print these sequences Hw4Pr2 Hw4Pr3Monte Carlo Monty Hall ( for ) Virtual Monty Hall ( while ) print the sum of the first four sequences, too … N-Z all others welcome! Hw4Pr1) Improved Math MenuPair Programming Problem

Summary for loop examples while loop examples statements and shortcuts for changing variables for (int i=12 ; i>=0 ; i-=2) { H.p( i + “ ” ); } int x = 3; for (int i=0 ; i<9 ; ++i) { H.p( x + “ ” ); x = x + 12; } x *= 10; num += 10; while ( true ) { String s = H.nw(); if (s.equals(“no”)) break; } ++i; i++;--i; i--; multiply x by 10increase num by 10increase i by 1decrease i by 1 prints prints continues until the user types “no”

“Quiz” Print the output of these loops: Names: A B C int s = 0; for (int x = 1 ; x < 5 ; ++x) { H.p( x + “ ” ); s = s + x; } H.pl(“\ns is ” + s); int i = 20; while (i > 0) { i /= 2; H.p( i + “ ” ); } for (int i = 10 ; i > 0 ; i+=1 ) { H.p( i + “ ” ); }

“Quiz”, part Write a loop to print this sequence: 9 terms total terms total Write a loop to print this sequence: Hint: Use a for loop with an if inside it! Hint: Use a for loop with a for loop inside it!

A C int s = 0; for (int x = 1 ; x < 5 ; ++x) { H.p( x + “ ” ); s = s + x; } H.pl(“\ns is ” + s); int i = 20; while (i > 0) { i /= 2; H.p( i + “ ” ); } for (int i = 10 ; i > 0 ; i = i-2) { H.p( i + “ ” ); } prints B

int s = 0; for (int x = 1 ; x < 5 ; ++x) { H.p( x + “ ” ); s = s + x; } H.pl(“\ns is ” + s); int i = 20; while (i > 0) { i /= 2; H.p( i + “ ” ); } for (int i = 10 ; i > 0 ; i = i-2) { H.p( i + “ ” ); } prints A C B

int s = 0; for (int x = 1 ; x < 5 ; ++x) { H.p( x + “ ” ); s = s + x; } H.pl(“\ns is ” + s); int i = 20; while (i > 0) { i /= 2; H.p( i + “ ” ); } for (int i = 10 ; i > 0 ; i = i-2) { H.p( i + “ ” ); } prints

int s = 0; for (int x = 1 ; x < 5 ; ++x) { H.p( x + “ ” ); s = s + x; } H.pl(“\ns is ” + s); int i = 20; while (i > 0) { i /= 2; H.p( i + “ ” ); } for (int i = 10 ; i > 0 ; i = i-2) { H.p( i + “ ” ); } prints s is 10 A C B

Write a loop to print this sequence: 9 terms total int x = 0; for (int i=0 ; i<9 ; ++i) { H.p( x + “ ” ); if ( i%2 == 0 ) { x = x + 1; } else { x = x * 2; } i = 0 i = 1 i = 2 i = 3 i = 4 i = 5 i = 6 i = 7 i = 8 shorter?

Write a loop to print this sequence: 9 terms total int x = 0; for (int i=0 ; i<9 ; ++i) { H.p( x + “ ” ); if ( i%2 == 0 ) ++x; else x *= 2; } i = 0 i = 1 i = 2 i = 3 i = 4 i = 5 i = 6 i = 7 i = 8 ifs and elses have one-line bodies (“blocks”) if no curly braces are used

Write a loop to print this sequence: 9 terms total for (int i=1 ; i<10 ; ++i) { for (int j=1 ; j<=i ; ++j) { H.p(0); } H.p(“ ”); } i = 1 i = 2 i = 3 i = 4 j = 1 j = 3 j = 1 j = 2 j = 1 j = 2 j = 3j = 1 j = 2j = 4 shorter?

Write a loop to print this sequence: 9 terms total for (int i=1 ; i<10 ; ++i) { for (int j=1 ; j<=i ; ++j) H.p(0); H.p(“ ”); } i = 1 i = 2 i = 3 i = 4 j = 1 j = 3 j = 1 j = 2 j = 1 j = 2 j = 3j = 1 j = 2j = 4 ifs and elses have one-line bodies (“blocks”) if no curly braces are used

Variables: a life story... int sum = 0; for ( int x = 0 ; x < 6 ; ++x ) { H.p( x + “ ” ); sum = sum + x; } H.pl(“sum is ” + sum); (1) Birth (of sum and x )

Variables: a life story... int sum = 0; for ( int x = 0 ; x < 6 ; ++x ) { H.p( x + “ ” ); sum = sum + x; } H.pl(“sum is ” + sum); (1) Birth (of sum and x ) (2) Growth

Variables: a life story... int sum = 0; for ( int x = 0 ; x < 6 ; ++x ) { H.p( x + “ ” ); sum = sum + x; } H.pl(“sum is ” + sum); A variable’s scope is the block of code in which it is declared. (1) Birth (of sum and x ) A variable only exists until the closing curly brace of its scope... (2) Growth (3) Death (of x )

Variables: a life story... int sum = 0; for ( int x = 0 ; x < 6 ; ++x ) { H.p( x + “ ” ); sum = sum + x; } H.pl(“sum is ” + sum); int sum = 0; for … next loop here … (1) Birth (of sum and x ) (2) Growth (3) Death (of x ) Why will java complain about this ?!?

Variables: a life story... int sum = 0; for ( int x = 0 ; x < 6 ; ++x ) { H.p( x + “ ” ); sum = sum + x; } H.pl(“sum is ” + sum); sum = 0; for … next loop here … (1) Birth (of sum and x ) (2) Growth (3) Death (of x ) You can reuse But you can’t redeclare !

What’s this all for ? Program for factorial input: an integer n output: the integer n! case 1: { H.pl(“Type an integer n and I will print n!”); int n = H.ni(); // we have n – we need n! } Use the same idea for creating powers !

Extreme Looping with while No variable or expression is needed! H.pl(“It keeps on”); while ( true ) { H.pl(“going and”); } worry later about how to escape !

Extreme Looping with while No variable or expression is needed! H.pl(“It keeps on”); while ( true ) { H.pl(“going and”); int escape = H.randInt(1,100); if (escape == 100) { break; } worry later about how to escape ! here is how to quit – use break !

“User – friendly” code long myNumber = H.randLong(0, L); while ( true ) { H.pl(“I’m thinking of a positive integer”); H.pl(“If you guess it, you may leave.”); H.pl(“Otherwise, you must continue…\n”); H.p(“What is your guess? ”); int yourGuess = H.ni(); if ( yourGuess == myNumber ) { break; // let me out ! } A break breaks out of the enclosing switch, for, or while.

“User – friendly” code long myNumber = H.randLong(0, L); while ( true ) { H.pl(“I’m thinking of a positive integer”); H.pl(“If you guess it, you may leave.”); H.pl(“Otherwise, you must continue…\n”); H.p(“What is your guess? ”); int yourGuess = H.ni(); if ( yourGuess == myNumber ) { break; // let me out ! } H.p(“Would you like to continue playing? ”); String answer = H.nl(); if (answer == “no”) break; } much friendlier! same as before

Monty Hall Let’s make a deal ’63-’86 Sept inspiring the “Monty Hall paradox”

Monte Carlo Monty Hall Suppose you always switch to the other door... What are the chances that you will win the car ? Hw4Pr3) Monte Carlo Monty Hall Run it (randomly) 1000 times and see!

The two Monte Carlos Monte Carlo casino, Monaco Making random numbers work for you! Monte Carlo methods, Math/CS math hw cs hw physics hw Hum hw

Summary for loop examples while loop examples statements and shortcuts for changing variables for (int i=12 ; i>=0 ; i-=2) { H.p( i + “ ” ); } int x = 3; for (int i=0 ; i<9 ; ++i) { H.p( x + “ ” ); x = x + 12; } x *= 10; num += 10; while ( true ) { String s = H.nw(); if (s.equals(“no”)) break; } ++i; i++;--i; i--; multiply x by 10increase num by 10increase i by 1decrease i by 1 prints prints continues until the user types “no”

Hw4, Pr1, Option 2: integration!

Prof. Jacobsen goes hungry...

Monte Carlo in action Suppose you roll two dice. What are the chances that you roll doubles? int doublesCount = 0; for (int i=0 ; i<1000 ; ++i) { int d1 = H.randInt(1,6); int d2 = H.randInt(1,6); if ( d1 == d2 ) { ++doublesCount; } H.pl(“We rolled ” + doublesCount + “ doubles.”); one roll of the dice 1000 times count the number of doubles rolled set up a variable to count the number of doubles rolled

Lab Today I’d suggest starting by writing the for loops in Hw4Pr1 then move on to the more involved examples use loops to print these sequences Hw4Pr2 Hw4Pr3Monte Carlo Monty Hall ( for ) Virtual Monty Hall ( while ) print the sum of just the first four sequences, too … N-Z and any others…

Hw4, Pr1, Option 4: random sums See the Improved Moth Menu for working example code at case 4: { Histogram h = new Histogram(); for (int i=0 ; i<50000 ; ++i) h.addPoint(Math.random()); outerFrame.updateSize(); break; } Your task: plot sums of random numbers min x is ~0 max x is ~1 current plot: random numberscurrent code: random numbers

Variables: a life story... for ( int i = 0 ; i < 6 ; ++i ) { int x = 1; H.out.print( x + “ ” ); x = x*3; } A variable’s scope is the block of code in which it is declared. (1) Birth (of x and i ) (2) Growth (3) Death A variable only exists until the closing curly brace of its scope...

A variable’s scope is the block of code in which it is declared. (1) Birth (of x and i ) (3) Death A variable only exists until the closing curly brace of its scope...

A variable’s scope is the block of code in which it is declared. (2) Growth (3) Death A variable only exists until the closing curly brace of its scope...

Variables: a life story... for ( int i = 0 ; i < 6 ; ++i ) { int x = 1; H.out.print( x + “ ” ); x = x*3; } A variable’s scope is the block of code in which it is declared. (1) Birth (of x and i ) (2) Growth (3) Death A variable only exists until the closing curly brace of its scope...

Variables: a life story... for ( int i = 0 ; i < 6 ; ++i ) { int x = 1; H.out.print( x + “ ” ); x = x*3; } A variable’s scope is the block of code in which it is declared. (1) Birth (of x and i ) (2) Growth (3) Death A variable only exists until the closing curly brace of its scope...

Back inside the machine... Shortcuts for changing variables: i++;++i; int i = 33; i = i + 1; i += 1;

int amoebas = ; amoebas = amoebas * 2; double hwToGo = 11.0; hwToGo = hwToGo - 1; long u235 = L; u235 = u235 / 2;

Program design top-down software engineering in general: start with program skeleton boolean done = false; while ( !done ) { add details to structure compile && run program if ( everything == OK ) done = true; }

Anatomy of a for loop for ( int i = 0 ; i < 9 ; ++i ) { H.out.println(“i is ” + i); } the “for” block #0 - create and initialize loop variables #1 - check the test condition #2 - execute all of the code in the “for” block #3 - update loop variables as desired; goto #1 if false, stop looping & jump past the “for” block if true, continue looping initialization statement test variable updates

Anatomy of a for loop for ( int i = 0 ; i < 9 ; ++i ) { H.out.println(“i is ” + i); } #0 - create and initialize loop variables initialization statement int i 0

Anatomy of a for loop for ( int i = 0 ; i < 9 ; ++i ) { H.out.println(“i is ” + i); } #0 - create and initialize loop variables #1 - check the test condition if false, stop looping & jump past the “for” block if true, continue looping test int i 0

Anatomy of a for loop for ( int i = 0 ; i < 9 ; ++i ) { H.out.println(“i is ” + i); } #0 - create and initialize loop variables #1 - check the test condition #2 - execute all of the code in the “for” block if false, stop looping & jump past the “for” block if true, continue looping the “for” block i is 0 int i 0 output

Anatomy of a for loop for ( int i = 0 ; i < 9 ; ++i ) { H.out.println(“i is ” + i); } #0 - create and initialize loop variables #1 - check the test condition #2 - execute all of the code in the “for” block #3 - update loop variables as desired; goto #1 if false, stop looping & jump past the “for” block if true, continue looping variable updates i is 0 output int i 1

Execution of a for loop for ( int i = 0 ; i < 9 ; ++i ) { H.out.println(“i is ” + i); } output:

Execution of a for loop for ( int i = 0 ; i < 9 ; ++i ) { H.out.println(“i is ” + i); } i is 0 output: start continue looping if true int i 0 1 before after

continue looping if true Execution of a for loop for ( int i = 0 ; i < 9 ; ++i ) { H.out.println(“i is ” + i); } i is 0 i is 1 output: start int i 1 2 before after

continue looping if true Execution of a for loop for ( int i = 0 ; i < 9 ; ++i ) { H.out.println(“i is ” + i); } i is 0 i is 1 i is 2 output: start int i 2 3 before after

Execution of a for loop for ( int i = 0 ; i < 9 ; ++i ) { H.out.println(“i is ” + i); } i is 0 i is 1 i is 2 … i is 8 output: start int i 8 9 before after continue looping if true

Execution of a for loop for ( int i = 0 ; i < 9 ; ++i ) { H.out.println(“i is ” + i); } i is 0 i is 1 i is 2 … i is 8 output: start int i 8 9 before after jump to end of for loop if false continue looping if true

Monty Hall Let’s make a deal ’63-’86 Sept inspiring the “Monty Hall paradox”

Monte Carlo Monte Carlo casino, Monaco Estimating a value (usually a probability) by playing an appropriate game over and over. Monte Carlo methods, Math/CS

“Quiz” Print the output of these loops: Names: A B C int s = 0; for (int x = 1 ; x < 5 ; ++x) { H.p( x + “ ” ); s = s + x; } H.pl(“\ns is ” + s); int i = 20; while (i > 0) { i /= 2; H.p( i + “ ” ); } for (int i = 10 ; i > 0 ; i = i-2) { H.p( i + “ ” ); }

“Quiz”, part Write a loop to print this sequence: 9 terms total terms total Write a loop to print this sequence: Hint: Use a for loop with an if inside it! Hint: Use a for loop with a for loop inside it!

“Quiz”, part What code (using for ) will print 9 terms total Hw4Pr1) Option #1: sequences

Mixing it up... Hw4Pr1) Option #1: sequences … What code (using for ) will print 9 terms total

User - friendly code boolean playAgain = true; long mynumber = (long)(Math.random()* L); while ( playAgain ) { H.pl(“I’m thinking of a positive integer”); H.pl(“If you guess it, you may leave.”); H.pl(“Otherwise, you must continue…\n”); H.p(“What is your guess? ”); int yourguess = H.ni(); if ( yourguess == mynumber ) { playAgain = false; // let me out ! }

Variables: a life story... for ( int i = 0 ; i < 6 ; ++i ) { int x = 1; H.p( x + “ ” ); x = x*3; }

Variables: a life story... for ( int i = 0 ; i < 6 ; ++i ) { int x = 1; H.p( x + “ ” ); x = x*3; } A variable’s scope is the block of code in which it is declared. (1) Birth (of x and i ) (2) Growth A variable only exists until the closing curly brace of its scope...

Variables: a life story... for ( int i = 0 ; i < 6 ; ++i ) { int x = 1; H.p( x + “ ” ); x = x*3; } A variable’s scope is the block of code in which it is declared. (1) Birth (of x and i ) (2) Growth (3) Death A variable only exists until the closing curly brace of its scope...

Monty Hall program design top-down software engineering HW4PR3) Virtual Monty Hall write program skeleton while ( true ) { add more details compile && run program if ( everything == OK ) break; } H.pl(“Time to work on Chem...”);

Write a loop to print this sequence: 9 terms total for (int i=1 ; i<10 ; ++i) { for (int j=1 ; j<=i ; ++j) { H.p(0); } H.p(“ ”); } i = 1 i = 2 i = 3 i = 4 j = 1 j = 3 j = 1 j = 2 j = 1 j = 2 j = 3j = 1 j = 2j = 4 shorter?

Variables: a life story... int sum = 0; for ( int x = 0 ; x < 6 ; ++x ) { H.p( x + “ ” ); sum = sum + x; } H.pl(“sum is ” + sum); A variable’s scope is the block of code in which it is declared. (1) Birth (of sum and x ) A variable only exists until the closing curly brace of its scope... (2) Growth (3) Death (of x )

Variables: a life story... int sum = 0; for ( int x = 0 ; x < 6 ; ++x ) { H.p( x + “ ” ); sum = sum + x; } H.pl(“sum is ” + sum); sum = 0; for … next loop here … (1) Birth (of sum and x ) (2) Growth (3) Death (of x ) You can reuse But you can’t redeclare !

What’s this all for ? Program for factorial input: an integer n output: the integer n! case 1: { H.pl(“Type an integer n and I will print n!”); int n = H.ni(); // we have n – we need n! } Use the same idea for creating powers !

Extreme Looping with while No variable or expression is needed! H.pl(“It keeps on”); while ( true ) { H.pl(“going and”); double r = Math.random(); if (r > 0.99) { break; } worry later about how to escape ! here is how to quit – use break !

“User – friendly” code long myNumber = (long)(Math.random()* L); while ( true ) { H.pl(“I’m thinking of a positive integer”); H.pl(“If you guess it, you may leave.”); H.pl(“Otherwise, you must continue…\n”); H.p(“What is your guess? ”); int yourGuess = H.ni(); if ( yourGuess == myNumber ) { break; // let me out ! } A break breaks out of the enclosing switch, for, or while.