Lecture 9:The While Loop + Math methods AP Computer Science Principles

Slides:



Advertisements
Similar presentations
Building Java Programs
Advertisements

1 MATH METHODS THAT RETURN VALUES. 2 JAVA'S MATH CLASS.
Return values.
Copyright 2011 by Pearson Education Building Java Programs Chapter 3 Lecture 3-2: Return values, Math, and double reading: 3.2,
Building Java Programs
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Parameters, Return, and Interactive Programs with Scanner.
Copyright 2008 by Pearson Education Building Java Programs Chapter 3 Lecture 3-2: Return; double ; System.out.printf reading: 3.2, 3.5, 4.4 videos: Ch.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops reading: 4.1, 5.1.
1 Data types, operations, and expressions Continued l Overview l Assignment statement l Increment and Decrement operators l Short hand operators l The.
Topic 10 return values, Math methods Based on slides bu Marty Stepp and Stuart Reges from " Thinking like a computer.
Building Java Programs Chapter 5 Program Logic and Indefinite Loops Copyright (c) Pearson All rights reserved.
Copyright 2011 by Pearson Education Building Java Programs Chapter 3 Lecture 7: Return values, Math, and double reading: 3.2,
Topic 14 while loops and loop patterns Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from
Copyright 2010 by Pearson Education 1 Building Java Programs Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops reading: 4.1, 5.1.
Building Java Programs Program Logic and Indefinite Loops.
29 January 2016Birkbeck College, U. London1 Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems.
1 BUILDING JAVA PROGRAMS CHAPTER 5 PROGRAM LOGIC AND INDEFINITE LOOPS.
1 Building Java Programs Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops reading: 5.1 – 5.2.
Copyright 2011 by Pearson Education Building Java Programs Chapter 3 Lecture 3-2: Return values, Math, and double reading: 3.2,
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Variables, Operators, and Expressions
Lecture 8: Return values and math
Categories of loops definite loop: Executes a known number of times.
Lecture 6: While Loops and the Math Class
CSc 110, Autumn 2017 Lecture 17: while Loops and Sentinel Loops
REPETITION CONTROL STRUCTURE
Building Java Programs
Building Java Programs
BIL 104E Introduction to Scientific and Engineering Computing
Building Java Programs
TMF1414 Introduction to Programming
Building Java Programs
Building Java Programs
Introduction to Programming
Topic 10 return values, Math methods
CSc 110, Autumn 2016 Lecture 12: while Loops, Fencepost Loops, and Sentinel Loops Adapted from slides by Marty Stepp and Stuart Reges.
CSc 110, Spring 2017 Lecture 11: while Loops, Fencepost Loops, and Sentinel Loops Adapted from slides by Marty Stepp and Stuart Reges.
Building Java Programs Chapter 4
Looping.
Building Java Programs
Building Java Programs
Lecture 7: Graphics, return values and math
Java's Math class Method name Description Math.abs(value)
CSc 110, Spring 2018 Lecture 16: Fencepost Loops and while loops
Topic 14 while loops and loop patterns
Building Java Programs
Building Java Programs
Topic 10 return values, Math methods
Lecture 9: Arrays Building Java Programs: A Back to Basics Approach
Lecture 5: For Loops Building Java Programs: A Back to Basics Approach
Lecture 6: While Loops and the Math Class
Lecture 5: Basic Java Syntax AP Computer Science Principles
Lecture 8:The For Loop AP Computer Science Principles.
Introduction to Programming with Python
Lecture 6: Conditionals AP Computer Science Principles
Building Java Programs
Loop problem Write a method printLetters that prints each letter from a word separated by commas. For example, the call: printLetters("Atmosphere") should.
Building Java Programs
CSE 142 Lecture Notes Global Constants, Parameters, Return Values
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
CSE 142, Spring 2013 Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops reading: 5.1 – 5.2.
Building Java Programs
Types of loops definite loop: A loop that executes a known number of times. Examples: Repeat these statements 10 times. Repeat these statements k times.
Building Java Programs
Building Java Programs
Lecture 11: return values and math
Presentation transcript:

Lecture 9:The While Loop + Math methods AP Computer Science Principles

while loops

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; // initialization while (num <= 200) { // test print(num + " "); num = num * 2; // update // output: 1 2 4 8 16 32 64 128

Example while loop // finds the first factor of 91, other than 1 int n = 91; int factor = 2; while (n % factor != 0) { factor++; } 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.

Curly braces {} Curly braces mark the body of methods, for/while 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) { print(i + ” “); } for (int i = 5; i <= 25; i+=1)

Curly braces {} The following are also equivalent. if (x <= 1) { print(x + ” “); } if (x <= 1)

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

An example int count = 10; while(count > 9) { count++; } Infinite loop!!

Another Example int count = 10; while(count < 13) println(count + “ ”); count++; Still infinite loop!!

One More int count=10; while(count<13) { println(count + “ ”); } Correct!

float vs double float: 32-bit data type representing real numbers to about 7 decimal places. double: 64-bit data type representing real numbers to about 16 decimal places. Since Processing is graphics intensive, it is recommended that floats are used instead of doubles. In fact, float is the default type for decimal numbers in Processing. All of the built-in math functions in Processing returns floats. The math functions from the standard Math library in Java returns doubles. double a = Math.sqrt(9); // a = 3.0 but is a double float b = sqrt(9); // b = 3.0 but is a float

Processing's Math methods Method name Description abs(value) absolute value(int or float) ceil(value) rounds up(int) exp(value) exponential, base e log(value) logarithm, base e map(x,x1,x2,y1,y2) linear map x from [x1,x2] to [y1,y2] pow(base, exp) base to the exp power(float) random(value) random float from [0,value) random(value1, value2) random float from [value1,value2) round(value) nearest whole number(int) sqrt(value) square root sin(value),cos(value) tan(value) sine/cosine/tangent of an angle in radians atan(value) atan2(dy,dx) inverse tangent (-PI/2, PI/2) inverse tangent (-PI, PI) degrees(value) radians(value) convert degrees to radians and back Constant Description PI 3.1415926...

Calling Math methods Examples: float squareRoot = sqrt(121.0); println(squareRoot); // 11.0 int absoluteValue = abs(-50); println(absoluteValue); // 50 println(pow(2,-3)); // 0.125 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.).

Type casting(Processing) type cast: A conversion from one type to another. To promote an int into a float to get exact division from / To truncate a float from a real number to an integer Syntax: float(expression) or int(expression) float result = float(19) / 5; // 3.8 int result2 = int(result); // 3 int x = int(pow(10, 3)); // 1000 Note: This casting method is unique to Processing and only works with float and int.

Random Numbers

Random numbers random(value) produces a random float from 0(inclusive) to value exclusive. float x = random(5); // 0.0 <= x < 5.0 float y = 3 * random(4); // 0.0 <= y < 12.0 float z = random(4)+ 2; // 2.0 <= z < 6.0 random(value1, value2) produces a random float from value1(inclusive) to value2 exclusive. float x = random(5,10); // 5.0 <= x < 10.0 float y = random(-3,-1); // -3.0 <= y < -1.0

Random Integers How do we generate random integers? int x = int(random(5)); // random integer 0 to 4 inclusive. int y = int(random(3,9)); // random integer 3 to 8 inclusive. int z = int(random(0,2)); // random integer 0 or 1 // useful for heads/tails

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. The while loops are used for indefinite loops. 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.

Example: Roll A Die Write a method rollDie that simulates a die rolling experiment. The method repeatedly rolls a die and display the output, until there are a total of four aces (1). The method then prints out a success message that includes the total number of rolls. rollDie(); 1 2 2 5 1 6 4 1 2 1 Got 4 aces in 10 rolls! 1 1 1 5 1 Got 4 aces in 5 rolls!

Answer to rollDie void rollDie(){ int roll = 0; int aces = 0; while(aces < 4){ int die = int(random(1,7)); //1 to 6 if(die == 1) aces++; roll++; print(die + " "); } //found 4 aces println(); println("Got 4 aces in " + roll + " rolls."); 20

Lab 1 Go to my codingbat homepage at(BOOKMARK THIS PAGE): https://codingbat.com/home/lnguyen8@bostonpublicschools.org And do all the problems from the ”while” page. This problems can be done with a for loop, but YOU MUST USE A WHILE LOOP! Remember to login to save your work!

Lab 2 Write a method tossCoin that accepts an integer input n and simulates a coin toss experiment. The method repeatedly tosses a coin and display the output, H for heads and T for tails, until there are a total of n heads. The method then prints out a success message that includes the total number of toss. tossCoin(4); H T T H H T H Got 4 heads in 7 tosses! tossCoin(6); H T H H T T T H H T H Got 6 heads in 11 tosses!

Lab 2 Write a method tossFour that simulates a coin toss experiment. The method repeatedly tosses a coin and display the output, H for heads and T for tails, until there are a total of FOUR heads in a row. The method then prints out a success message that includes the total number of toss. tossFour(); H T T H H T H H H H Got 4 heads in a row in 10 tosses! H H T H H H H Got 4 heads in a row in 7 tosses!

Lab 2 Outline Write the setup() method to test your methods. void setup(){ } void tossCoin(int n) { void tossFour() 24

Lab 3 In the lab from the previous lecture, you drew horizontal and vertical lines to form a grid. Make a copy of that lab and modify it to use while loops instead of for loops.

Homework Read and reread these lecture notes. Complete the problem set on While Loops. Complete the labs.

References Part of this lecture is taken from the following book. 1) Stuart Reges and Marty Stepp. Building Java Programs: A Back to Basics Approach. Pearson Education. 2008.