CIS 111 Lecture Notes - Lecture 4: Syntactic Sugar, While Loop, Iterator

56 views2 pages
Chpt 5 (loops), Chpt 12 (Strings), Chpt 15 (Math.random), Chpts 21-23 (DOM) (Wk 4)
In Class This Week
o Chpt 5: Loops
o Chpt 12-13: Strings
o Chpt 5: Do While Loop
Function + loop + if
o Example: Count primes
var countPrimes(n){
var count=0;
//generate and test
for(var i-1; i<=n;++i){
if(isPrime(i)){
++count;
}}
return count;
};
Math.Random
o Returns a pseudo-random # in the range [0 to 1] which you can then scale to your
desired range
Math.random()=>.7259735443837176
//return a random number between 1 and 10
Math.floor((Math.random() * 10) + 1);
//return a random number between 1 and 6
Math.floor((Math.random() *6) + 1);
//return 0 (tails) or 1 (heads)
var flipCoin=function(){
return Math.floor((Math.random() *2));
};
alert(flipCoin());
alert(flipCoin());
//return 0 (tails) or 1 (heads)
var flipCoin=function(){
return Math.floor((Math.random() *2));
};
var flipCount=0, coin = 0; //1. Init loop control variable
//flip coin until heads
while(coin !=1){
coin=flipCoin(); //2. Update
++flipCount;
}
alert(“Heads in ” + flipCount + “ flips.”);
Unlock document

This preview shows half of the first page of the document.
Unlock all 2 pages and 3 million more documents.

Already have an account? Log in

Get access

Grade+
$40 USD/m
Billed monthly
Grade+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
10 Verified Answers
Class+
$30 USD/m
Billed monthly
Class+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
7 Verified Answers

Related Documents

Related Questions