Skip to content

Instantly share code, notes, and snippets.

@annajmorton
Created June 2, 2016 14:11
Show Gist options
  • Select an option

  • Save annajmorton/d141e02cbca4a487a17e124e12d7fee5 to your computer and use it in GitHub Desktop.

Select an option

Save annajmorton/d141e02cbca4a487a17e124e12d7fee5 to your computer and use it in GitHub Desktop.
Exercise Solutions - While Loops

While Loops

Please follow the instructions below.

  1. Create an HTML file named while_loop_js.html within the ~/vagrant-lamp/sites/codeup.dev/public folder on your Mac.
  2. An ice cream seller can't go home until she sells all of her cones. Write a JS program that generates a random number between 50 and 100 representing the amount of cones to sell. Your code should generate numbers between 1 and 5, simulating the amount of cones being bought by her clients. Use a do-while loop to log to the console the amount of cones sold to each person. This is how you get the random numbers.
// This is how you get a random number between 50 and 100
var allCones = Math.floor(Math.random() * 50) + 50;
// This is how you get a random number between 1 and 5
var cones = Math.floor(Math.random() * 5) + 1;

The output should be similar to the following:

5 cones sold...  // if there are enough cones
Cannot sell you 6 cones I only have 3...  // If there are not enough cones
Yay! I sold them all! // If there are no more cones
  ```
solution :

  ```js
  	
  var allCones = Math.floor(Math.random() * 50) + 50;
  var cones;
  var remaining = allCones;
  var msg;
  
  do{
  
  	cones = Math.floor(Math.random() * 5) + 1;
  	remaining -= cones; 
  	msg = cones + ' cones sold...';
  	if (remaining<0) {
  		msg = 'Cannot sell you ' + cones + ' cones I only have ' + (remaining + cones) +' ...';
  	};
  	if (remaining==0) {
  		msg = 'Yay! I sold them all!';
  	};
  
  	console.log(msg);
  
  }while(remaining>0);
  		
  ```



1. Use inline JavaScript to create a `while` loop that uses `console.log()` to create the output shown below.

  ```
          2
          4
          8
          16
          32
          64
          128
          256
          512
          1024
          2048
          4096
          8192
          16384
          32768
          65536
          
  ```
  solution:
  
  ```js
  var num = 2;
  while(num < 65536){
  	console.log(num+=num);
  };
  ```

1. Finally, save your work, commit the changes to your git repository, and push to GitHub.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment