Example: Monte Carlo Simulation 1

Similar documents
Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Exercise (Revisited)

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

switch-case Statements

Arithmetic Compound Assignment Operators

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 89 / 137

Common Errors double area; 3 if (r > 0); 4 area = r r 3.14; 5 System.out.println(area); 6... Zheng-Liang Lu Java Programming 101 / 141

Nested Loops. A loop can be nested inside another loop.

Arithmetic Compound Assignment Operators

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 88 / 133

Logic is the anatomy of thought. John Locke ( ) This sentence is false.

1 class Lecture4 { 2 3 "Loops" / References 8 [1] Ch. 5 in YDL 9 / Zheng-Liang Lu Java Programming 125 / 207

Example. Write a program which generates 2 random integers and asks the user to answer the math expression.

Example. Generating random numbers. Write a program which generates 2 random integers and asks the user to answer the math expression.

++x vs. x++ We will use these notations very often.

Scanner Objects. Zheng-Liang Lu Java Programming 82 / 133

Midterm Examination (MTA)

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

1 class Lecture5 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199

Nested Loops ***** ***** ***** ***** ***** We know we can print out one line of this square as follows: System.out.

Loops. CSE 114, Computer Science 1 Stony Brook University

IEEE Floating-Point Representation 1

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Iteration: Intro. Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times. 2. Posttest Condition follows body Iterates 1+ times

Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

Exercise. Write a program which allows the user to enter the math grades one by one (-1 to exit), and outputs a histogram.

Data Types. 1 You cannot change the type of the variable after declaration. Zheng-Liang Lu Java Programming 52 / 87

Iteration statements - Loops

Motivations. Chapter 5: Loops and Iteration. Opening Problem 9/13/18. Introducing while Loops

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

Fundamentals of Programming Data Types & Methods

Some Sample AP Computer Science A Questions - Solutions

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Controls Structure for Repetition

Top-Down Program Development

Introduction to Java & Fundamental Data Types

Arrays. Eng. Mohammed Abdualal

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Values in 2 s Complement

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Chapter 4: Control structures. Repetition

CS1150 Principles of Computer Science Loops (Part II)

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Variable Scope. The variable scope is the range of the program where the variable can be referenced.

Date: Dr. Essam Halim

Flow Control. CSC215 Lecture

Repetition, Looping. While Loop

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Chapter 4: Control structures

School of Computer Science CPS109 Course Notes 6 Alexander Ferworn Updated Fall 15. CPS109 Course Notes 6. Alexander Ferworn

Introduction to the Java Basics: Control Flow Statements

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

CSC 1051 Villanova University. CSC 1051 Data Structures and Algorithms I. Course website:

Problem Solving With Loops

STUDENT LESSON A12 Iterations

Loops! Step- by- step. An Example while Loop. Flow of Control: Loops (Savitch, Chapter 4)

Last Class. While loops Infinite loops Loop counters Iterations

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

Java Loop Control. Programming languages provide various control structures that allow for more complicated execution paths.

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I

Flow of Control: Loops. Chapter 4

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters

Introduction to Programming Using Java (98-388)

COMP-202 Unit 4: Programming with Iterations

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

1 Short Answer (10 Points Each)

PROGRAMMING FUNDAMENTALS

SAMPLE QUESTIONS FOR DIPLOMA IN INFORMATION TECHNOLOGY; YEAR 1

Computer Programming, I. Laboratory Manual. Experiment #3. Selections

Chapter 6. Repetition Statements. Animated Version The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

CSC 1051 Data Structures and Algorithms I

Motivation of Loops. Loops. The for Loop (1) Learning Outcomes

ECE 122. Engineering Problem Solving with Java

Loops. EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

CMSC 150 INTRODUCTION TO COMPUTING LAB WEEK 3 STANDARD IO FORMATTING OUTPUT SCANNER REDIRECTING

CS141 Programming Assignment #6

Repetition with for loops

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

CSC 1051 Data Structures and Algorithms I

Array. Array Declaration:

Repetition CSC 121 Fall 2014 Howard Rosenthal

CS141 Programming Assignment #5

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

SOFTWARE DEVELOPMENT 1. Control Structures 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

COMP 202 Java in one week

CMPT 125: Lecture 4 Conditionals and Loops

CEN 414 Java Programming

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Warmup : Name that tune!

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.

Motivation of Loops. Loops. The for Loop (1) Learning Outcomes

Transcription:

Example: Monte Carlo Simulation 1 Write a program which conducts a Monte Carlo simulation to estimate π. 1 See https://en.wikipedia.org/wiki/monte_carlo_method. Zheng-Liang Lu Java Programming 133 / 149

Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue: the loop skips this iteration right after a continue statement is executed. In practice, jump statements in loops should be conditioned. Zheng-Liang Lu Java Programming 134 / 149

Example: Primality Write a program which determines if the input integer is a prime number. Let x > 1 be any natural number. Then x is said to be a prime number if x has no positive divisors other than 1 and itself. It is then straightforward to check if it is prime by dividing x by all natural numbers smaller than x. For speedup, you can divide x by only numbers smaller than x. (Why?) Zheng-Liang Lu Java Programming 135 / 149

1... 2 Scanner input = new Scanner(System.in); 3 System.out.println("Enter x > 2?"); 4 int x = input.nextint(); 5 boolean isprime = true; 6 input.close(); 7 8 double upperbd = Math.sqrt(x); 9 for (int y = 2; y < upperbd; y++) { 10 if (x % y == 0) { 11 isprime = false; 12 break; 13 } 14 } 15 16 if (isprime) { 17 System.out.println("Prime"); 18 } else { 19 System.out.println("Composite"); 20 } 21... Zheng-Liang Lu Java Programming 136 / 149

Exercise (Revisited) Redo the cashier problem by using an infinite loop with a break statement. 1... 2 while (true) { 3 System.out.println("Enter price ( 1 to exit):"); 4 price = input.nextint(); 5 if (price == 1) break; 6 sum += price; 7 } 8 System.out.println("Total = " + sum); 9... Zheng-Liang Lu Java Programming 137 / 149

Another Example: Compounding Write a program which determines the holding years for an investment doubling its value. Let balance be the current amount, goal be the goal of this investment, and r be the annual interest rate. Then this investment should take at least n years so that the balance of the investment can double its value. Recall that the compounding formula is given by balance = balance (1 + r/100). Zheng-Liang Lu Java Programming 138 / 149

1... 2 int r = 18; // 18% 3 int balance = 100; 4 int goal = 200; 5 6 int years = 0; 7 while (balance <= goal) { 8 balance = (1 + r / 100.0); 9 years++; 10 } 11 12 System.out.println("Balance = " + balance); 13 System.out.println("Years = " + years); 14... Zheng-Liang Lu Java Programming 139 / 149

1... 2 int years = 0; // should be declared here; scope issue 3 for (; balance <= goal; years++) { 4 balance = (1 + r / 100.0); 5 } 6... 1... 2 int years = 1; // check this initial value 3 for (; true; years++) { 4 balance = (1 + r / 100.0); 5 if (balance > goal) break; 6 } 7... A for loop can be an infinite loop by setting true or simply leaving empty in the condition statement. An infinite for loop with an if-break statement is equivalent to a normal while loop. Zheng-Liang Lu Java Programming 140 / 149

Equivalence: while and for Loops (Concluded) In general, a for loop may be used if the number of repetitions is known in advance. If not, a while loop is preferred. Zheng-Liang Lu Java Programming 141 / 149

Nested Loops A loop can be nested inside another loop. Nested loops consist of an outer loop and one or more inner loops. Each time the outer loop is repeated, the inner loops are reentered, and started anew. Zheng-Liang Lu Java Programming 142 / 149

Example Multiplication table Write a program which displays the multiplication table. Zheng-Liang Lu Java Programming 143 / 149

Formatting Console Output You can use System.out.printf () to display formatted output on the console. 1... 2 double amount = 1234.601; 3 double interestrate = 0.00528; 4 double interest = amount interestrate; 5 System.out.printf("Interest = %4.2f", interest); 6... Zheng-Liang Lu Java Programming 144 / 149

By default, a floating-point value is displayed with 6 digits after the decimal point. Zheng-Liang Lu Java Programming 145 / 149

Multiple Items to Print Items must match the format specifiers in order, in number, and in exact type. If an item requires more spaces than the specified width, the width is automatically increased. By default, the output is right justified. You may try the plus sign (+), the minus sign (-), and 0 in the middle of format specifiers. Say % + 8.2f, % 8.2f, and %08.2f. Zheng-Liang Lu Java Programming 146 / 149

1... 2 public static void main(string[] args) { 3 for (int i = 1; i <= 9; ++i) { 4 for (int j = 1; j <= 9; ++j) { 5 System.out.printf("%3d", i j); 6 } 7 System.out.println(); 8 } 9 } 10... Zheng-Liang Lu Java Programming 147 / 149

Exercise: Coupled Loops Zheng-Liang Lu Java Programming 148 / 149

1 public class PrintStarsDemo { 2 public static void main(string[] args) { 3 // case (a) 4 for (int i = 1; i <= 5; i++) { 5 for (int j = 1; j <= i; j++) { 6 System.out.printf(" "); 7 } 8 System.out.println(); 9 } 10 11 // case (b), (c), (d) 12 // your work here 13 } 14 } Zheng-Liang Lu Java Programming 149 / 149