prisskreative
7/10/2014 - 3:20 AM

Loops

Loops

ex: 1
var counter = 0;  // start with 0
while ( counter <= 10 ) {
  console.log(counter);
  counter += 1; // add one each time
}


ex: 2

function randomNumber(upper){
	return Math.floor(Math.random() * upper ) + 1;
}

var counter = 0;  
while ( counter < 10 ) {
  var ranNum = randoNumber(6);
  document.write(ranNum + ' ');
  counter += 1; 
}


Ex 3
// upper limit of the random number
var upper = 10000; 

// number the computer needs to guess
var randomNumber = getRandomNumber(upper); 

// computer guesss
var guess;

// number of attempts
var attempts = 0;


// Random number function - reusable code
function getRandomNumber(upper){
	return Math.floor(Math.random() * upper ) + 1;
}

// if !== not equal too
while ( guess !== randomNumber ) {
  guess = getRandomNumber(upper);
  attempts += 1; 
}

document.write("<p>The random number was: " + randomNumber + "</p>");

document.write("<p>It took the computer " + attempts + " atempts to get it right.</p>");


Ex 4

var secret = prompt("What is the secret password?");

while ( secret !== "sesame" ) {
  secret = prompt("What is the secret password?");    
}

document.write("You know the secret password. Welcome.");


How to avoid endless loops.
---------------------------

use a condition that is false so the loop ends

//doesn't run
while(false){
}
// The Refactor Challenge
// ======================

// Improve JavaScript program by using loops and applying "DRY" programming principles.

// Solution 1
// ----------

var html = '';
var red;
var green;
var blue;
var rgbColor;


for (var i = Math.floor(Math.random() * 256 ); i <= 10; i += 0) {
  rgbColor = 'rgb(' + red + ',' + green + ',' + blue + ')';
  html += '<div style="background-color:' + rgbColor + '"></div>';
}

document.write(html);



// Solution 2
// ----------

var html = '';
var red;
var green;
var blue;
var rgbColor;

function randomRGB(){
	return Math.floor(Math.random() * 256 )
}

function randomColor(){
	var color = 'rgb(';
	color += randomRGB() + ',';
	color += randomRGB() + ',';
	color += randomRGB() + ',';
	return color
}

function print(message){
	document.write(message);
}

for (var i = 0; i <= 10; i += 0) {
  rgbColor = randomColor();
  html += '<div style="background-color:' + rgbColor + '"></div>';
}

document.write(html);

/*Repetitive tasks

Another thing that you will certainly want to do in your programs is 
perform repetitive tasks. The simplest way to accomplish this is with 
loops. Loops are blocks of code that run over and over again until a 
certain condition is met. The condition can be anything you can think of! 
Just make sure that part of your loop includes code that changes the 
condition so that it is eventually met. 


*/


var i;

for (i = 1;  i <= 42;  i = i + 1) {
    console.log(i);
}

//Huh?
//So what's going on there? Here's the structure of a for:

for (  [start];  [condition];  [after-each]  ) {
    [task-code]
}


/*Basically a for loop wants to run [task-code] a bunch of times. In our example the only code we want to run a bunch of times is printing the variable i. As for that other weird stuff:

[start] is code to run to set some initial state before your loop starts. In our example we just set the initial value of i to 1.
[condition] is the comparison to perform to decide whether or not to keep running the loop again. When i becomes greater than 42 our loop will stop.
[after-each] is the code to run after each time we go through the loop to change the condition. This is supposed to ensure that eventually the condition will not be met and so the loop will stop at some point. In our case, we are adding 1 to i so that we will get closer to 42 every time we go through the loop. Be careful because JavaScript will let you write a loop that never stops (we call them infinite loops).
Exercise
Write a for loop that sings! Starting with one, each run through the loop should print a bunch of la until you print out lalalalalalalalalala. Like this:



la
lala
lalala
...
lalalalalalalalalala


*/

var sing = "la";
var singlong = "lalalalalalalalalala";
for (var i = sing; i !=singlong; i += sing) {
    console.log(i);
}

// For Loops
============

// actions that need to run a particle number of times

// while loop
var counter = 0;  
while ( counter < 10 ) {
  document.write(counter);
  counter += 1; 
}

// for loop
for (var counter = 0; counter < 10; counter += 1) {
   document.write(counter);
}

for (var i = 0; i <= 9; i = i + 1) {
	console.log( i );
}
// 0 1 2 3 4 5 6 7 8 9


// div with numbers

var html = '';


for (var i = 1; i <= 10; i += 1) {
   html += '<div>' + i + '</div>'; // add to the html variable
}

document.write(html);

// fizz buzz

for (i = 1; i < 31; i++) { 
   if (i%3 === 0){
          console.log("fizz");
      }
   else if(i%5 === 0){
       console.log("buzz");
      }
   else{
       console.log(i);
      }
}

'do ... while' Loops

// this will alway execute do {} once



var randomNumber = getRandomNumber(10);
var guess;
var guessCount = 0;
var correctGuess = false; 

function getRandomNumber( upper ) {
  var num = Math.floor(Math.random() * upper) + 1; 
  return num;
}


do{
  // collect the players guess
  guess = prompt('I'm thinking of a number between 1 and 10.What is it?');

  // increase the guess counter
  guessCount += 1;

  // check if answer is correct
  if (parseInt(guess) === randomNumber){
     correctGuess = true;
  }

  }
// ! if is true make it false - if false make it true
while(! correctGuess )

document.write("You guess the number");
document.write(it took you ' + guessCount + ' tries to guess the number ' + randomNumber);
// Exiting Loops
// =============

//how to exits loops using the break statement.

// when the statement is not true

// break the loop

while (true){
  guess = prompt('Im thinking of a number between 1 and 10.What is it?');
  guessCount += 1;
  if (parseInt(guess) === randomNumber){
     correctGuess = true
     break;  }
}
/* Loops
=====

provide a way to repeat the same set of actions over and over again.

For example, creating a list of 100 random numbers, displaying 20 photos,

downloaded from a photo sharing website like Flickr, or repeatedly popping up

a prompt dialog until a visitor correctly enters an answer to a quiz question.*/


// Run something several times
// similar to if
// 10 would be true and run the code until false

var counter = 10;

while (counter) {
  console.log ("hello word");
  counter = counter - 1;
}