Lecture 6: While Loops and the Math Class

Similar documents
AP Computer Science A. Return values

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

Building Java Programs

AP Computer Science. Return values, Math, and double. Copyright 2010 by Pearson Education

Building Java Programs

Building Java Programs

Building Java Programs

Building Java Programs

Building Java Programs

CS 112 Introduction to Programming

CS 112 Introduction to Programming

Topic 12 more if/else, cumulative algorithms, printf

Building Java Programs Chapter 3

Redundant recipes. Building Java Programs Chapter 3. Parameterized recipe. Redundant figures

CSc 110, Spring Lecture 11: return values and math

Topic 14 while loops and loop patterns

CS110: PROGRAMMING LANGUAGE I

AP CS Java Syntax Summary: (version 3)

12. Numbers. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Building Java Programs

A Balanced Introduction to Computer Science, 3/E

A Balanced Introduction to Computer Science, 3/E David Reed, Creighton University 2011 Pearson Prentice Hall ISBN

CSE 373. Data Types and Manipulation; Arrays. slides created by Marty Stepp

AP CS Unit 3: Control Structures Notes

Introduction to Computer Science Unit 2. Notes

The Math Class. Using various math class methods. Formatting the values.

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

CSc 110, Autumn Lecture 10: return values and math

Chapter 5 Methods / Functions

Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent

To define methods, invoke methods, and pass arguments to a method ( ). To develop reusable code that is modular, easy-toread, easy-to-debug,

CT 229 Java Syntax Continued

CS 112 Introduction to Programming

Flow of Control of Program Statements CS 112 Introduction to Programming. Basic if Conditional Statement Basic Test: Relational Operators

Lecture 2: Operations and Data Types

AP CS Java Syntax Summary: (version 4)

Variables, Types, Operations on Numbers

Building Java Programs

Chapter 5 Methods. Modifier returnvaluetype methodname(list of parameters) { // method body; }

Lecture 9: Arrays. Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp. Copyright (c) Pearson All rights reserved.

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

Introduction to Computer Science Unit 2. Notes

Chapter 5 Methods. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University

Recap: Assignment as an Operator CS 112 Introduction to Programming

Chapter 6 Methods. Dr. Hikmat Jaber

Computer Programming I - Unit 2 Lecture 1 of 13

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Chapter 5 Methods. Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University

CIS133J. Working with Numbers in Java

CS 112 Introduction to Programming

Building Java Programs

Calculations, Formatting and Conversions

Review for Test 1 (Chapter 1-5)

CS 112 Introduction to Programming

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner

Topic 4 Expressions and variables

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

More types, Methods, Conditionals. ARCS Lab.

CONDITIONAL EXECUTION

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

Chapter 4 Mathematical Functions, Characters, and Strings

1.3 Conditionals and Loops

static int min(int a, int b) Returns the smaller of two int values. static double pow(double a,

SSEA Computer Science: Track A. Dr. Cynthia Lee Lecturer in Computer Science Stanford

AP Programming - Chapter 6 Lecture

Final Examination Semester 2 / Year 2011

Visual Programming. Lecture 2: More types, Methods, Conditionals

Chapter 4 Control Structures

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

M e t h o d s a n d P a r a m e t e r s

Building Java Programs

CS111: PROGRAMMING LANGUAGE II

Variables and data types

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Functions, Randomness and Libraries

Module 1: Types and Expressions

Elementary Programming

CS1150 Principles of Computer Science Loops (Part II)

Top-Down Program Development

Chapter 7. Iteration. 7.1 Multiple assignment

Building Java Programs

1.3 Conditionals and Loops. 1.3 Conditionals and Loops. Conditionals and Loops

Research Group. 2: More types, Methods, Conditionals

1.3 Conditionals and Loops

The Math Class (Outsource: Math Class Supplement) Random Numbers. Lab 06 Math Class

Term 1 Unit 1 Week 1 Worksheet: Output Solution

CS 312 Exam 1 Fall KG Kris Megan Roman Sonika

JAVASCRIPT BASICS. JavaScript Math Functions. The Math functions helps you to perform mathematical tasks

1.3 Conditionals and Loops

Introduction to Computer Science and Object-Oriented Programming

Important Java terminology

Assignment 2.4: Loops

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

CSC 1051 Data Structures and Algorithms I

AP CS Java Syntax Summary: (version 5)

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

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

Transcription:

Lecture 6: While Loops and the Math Class Building Java Programs: A Back to Basic Approach by Stuart Reges and Marty Stepp Copyright (c) Pearson 2013. All rights reserved.

while loops 2

Categories of loops definite loop: Executes a known number of times. The for loops we have seen are definite loops. Print "hello" 10 times. Find all the prime numbers up to an integer n. Print each odd number between 5 and 127. indefinite loop: One where the number of times its body repeats is not known in advance. Prompt the user until they type a non-negative number. Print random numbers until a prime number is printed. Repeat until the user has types "q" to quit. 3

The while loop while loop: Repeatedly executes its body as long as a logical test is true. while (test) { statement(s); } Example: int num = 1; while (num <= 200) { System.out.print(num + " "); num = num * 2; } // output: 1 2 4 8 16 32 64 128 // initialization // test // update 4

Example while loop // finds the first factor of 91, other than 1 int n = 91; int factor = 2; while (n % factor!= 0) { factor++; } System.out.println("First factor is " + factor); // output: First factor is 7 while is better than for because we don't know how many times we will need to increment to find the factor. 5

What s wrong? int count = 10; while(count > 9) { count++; } Infinite loop!! 6

Corrected int count = 10; while(count < 13) System.out.println(count + ); count++; Still infinite loop!! 7

Finally Corrected int count = 10; while(count < 13) { System.out.println(count + ); count++; } Correct! 8

Curly braces {} Curly braces mark the body of methods, for loops and conditional blocks. They are not necessary if the body or the block consists of only one statement. The following are equivalent. for (int i = 5; i <= 25; i+=1) { System.out.print(i + ); } for (int i = 5; i <= 25; i+=1) System.out.print(i + ); 9

Curly braces {} The following are also equivalent. if (x <= 1) { System.out.print(x + ); } if (x <= 1) Ssytem.out.print(x + ); 10

Curly braces {} The following are NOT equivalent. int sum = 0; for (int i = 1; i <= 10; i+=1) { System.out.print(i + ); sum += i; } int sum = 0; for (int i = 5; i <= 25; i+=1) System.out.print(i + ); sum += i; //error, why? 11

The Math Class

Static Methods The Math class has many useful static methods. To call a static method from a different class than the current point of your code, use the following syntax. Math.methodName(parameters); double answer = Math.sqrt(9.2); double a = Math.sin(3.67); int b = Math.round(5.6755); 13

Static Method Calling Calling a static method from a different class. public class Math{ public static int abs(int x) { } public static double sqrt(double x) { } } public class MyClass{ } public static void main(string[] args) { System.out.println(Math.abs(-5)); double y=math.sqrt(9.2); } 14

Java's Math class Method name Math.abs(value) Math.ceil(value) Math.floor(value) Description absolute value rounds up rounds down Math.log10(value) logarithm, base 10 Math.max(value1, value2) larger of two values Math.min(value1, value2) smaller of two values Math.pow(base, exp) base to the exp power Math.random() random double between 0 and 1 Math.round(value) Math.sqrt(value) Math.sin(value) Math.cos(value) Math.tan(value) Math.toDegrees(value) Math.toRadians(value) nearest whole number square root sine/cosine/tangent of an angle in radians convert degrees to radians and back Constant Description Math.E 2.7182818... Math.PI 3.1415926... 15

Calling Math methods Examples: double squareroot = Math.sqrt(121.0); System.out.println(squareRoot); // 11.0 int absolutevalue = Math.abs(-50); System.out.println(absoluteValue); // 50 System.out.println(Math.min(3, 7) + 2); // 5 The Math methods do not print to the console. Each method produces ("returns") a numeric result. The results are used as expressions (printed, stored, etc.). 16

Return return: To send out a value as the result of a method. The opposite of a parameter: Parameters send information in from the caller to the method. Return values send information out from a method to its caller. A call to the method can be used as part of an expression. -42 Math.abs(-42) main 42 2.71 3 Math.round(2.71) 17

Math questions Evaluate the following expressions: Math.abs(-1.23) Math.pow(3, 2) Math.pow(10, -2) Math.sqrt(121.0) - Math.sqrt(256.0) Math.round(Math.PI) + Math.round(Math.E) Math.ceil(6.022) + Math.floor(15.9994) Math.abs(Math.min(-3, -5)) Math.max and Math.min can be used to bound numbers. Consider an int variable named age. What statement would replace negative ages with 0? What statement would cap the maximum age to 40? 18

Math questions Write a method withinhalf which takes two double parameters and return true if they are within.5 of each other and false otherwise. withinhalf(4,5.1) // returns false withinhalf(3.4,3.9) // returns true withinhalf(3.9,3.4) // returns true withinhalf(-1.2,-1.1) // returns true public static boolean withhalf(double x, double y) { } return Math.abs(x - y) <=.5; 19

Quirks of real numbers Some Math methods return double or other non-int types. int x = Math.pow(10, 3); // ERROR: incompat. types Some double values print poorly (too many digits). double result = 1.0 / 3.0; System.out.println(result); // 0.3333333333333 The computer represents doubles in an imprecise way. System.out.println(0.1 + 0.2); Instead of 0.3, the output is 0.30000000000000004 20

Type casting type cast: A conversion from one type to another. To promote an int into a double to get exact division from / To truncate a double from a real number to an integer Syntax: (type) expression Examples: double result = (double) 19 / 5; // 3.8 int result2 = (int) result; // 3 int x = (int) Math.pow(10, 3); // 1000 21

More about type casting Type casting has high precedence and only casts the item immediately next to it. double x = (double) 1 + 1 / 2; // 1.0 double y = 1 + (double) 1 / 2; // 1.5 You can use parentheses to force evaluation order. double average = (double) (a + b + c) / 3; A conversion to double can be achieved in other ways. double average = 1.0 * (a + b + c) / 3; 22

Random Numbers

Random numbers Math.random() produces a number from 0(inclusive) to 1 exclusive. double x = Math.random(); // 0.0 <= x <1.0 double x = 3*Math.random(); // 0.0 <= x< 3.0 double x = Math.random()+2; // 2.0 <= x< 3.0 double x = 5*Math.random()+4; // 4.0<=x<9.0 In general, to produce a random real number in the range [low,high), double x = (high-low)*math.random()+low; Generate a random real value in [7.0,15.0). double x = 8 * Math.random() + 7; 24

Random Integers How do we generate random integers? int x = (int)(100*math.random()); // random integer 0 to 99 inclusive. int y = (int)(100*math.random())+4; // random integer 4 to 103 inclusive. int z = (int)(2*math.random()); // random integer 0 or 1, useful for heads/tails 25

More Examples int x = (int) Math.random()*5; // x=0 int y = (int)(6*math.random())-10; // integer from -10 to -5 inclusive. double z =3*Math.random()+5; //random double in [5,8) 26

For vs. While for(int i = 1; i <= 100; i++) { System.out.println(i); } This for loop executes 100 times. It is a definite loop. It is usually better to use a for loop as a definite loop. 27

For vs. While int x=3; while(x == 3) { System.out.println(x); } x=(int)(4*math.random()); // x is 0,1,2,or 3 This while loop executes an unknown number of times. It is a indefinite loop. It is usually better to use a while loop as an indefinite loop. 28

The do/while loop(not TESTED) do/while loop: Performs its test at the end of each repetition. Guarantees that the loop's {} body will run at least once. do { statement(s); } while (test); // Example: generate random numbers 0-9 until 7 // is generated. int rand=(int)(10*math.random()); ; do { System.out.print(rand+ "); rand=(int)(10*math.random()); } while (rand!= 7); 29

Lab Create a folder in CS50 called While for this lab. Write a method countfactors that returns the number of factors of an integer. Use a for loop. countfactors(24) returns 8 because 1, 2, 3, 4, 6, 8, 12, and 24 are factors of 24. Write a method isprime which returns whether or not an integer is prime. This method must call countfactors. Example: isprime(27) returns false and isprime(47) returns true. 30

Lab Write a static method named fourheads that repeatedly flips a coin until four heads in a row are seen. You should use Math.random() to give an equal chance to a head or a tail appearing. Each time the coin is flipped, what is seen is displayed (H for heads, T for tails). When four heads in a row are flipped a congratulatory message is printed. Here are possible outputs of two calls to fourheads: T T T H T H H H H Four heads in a row! T H T H T T T T T H H T H H H H Four heads in a row! 31

Lab Write a static method named printtwodigit that accepts an integer n as a parameter and that prints a series of n randomly generated numbers. The method should use Math.random() to select numbers in the range of 10 to 19 inclusive where each number is equally likely to be chosen. After displaying each number that was produced, the method should indicate whether the number 13 was ever selected ("we saw a 13!") or not ("no 13 was seen."). You may assume that the value of n passed is at least 0. You should an output similar to below. (see next slide) 32

33