Skip to content

Instantly share code, notes, and snippets.

@annajmorton
Created June 2, 2016 14:33
Show Gist options
  • Save annajmorton/9c82b0020117132855a0a5d2177497c5 to your computer and use it in GitHub Desktop.
Save annajmorton/9c82b0020117132855a0a5d2177497c5 to your computer and use it in GitHub Desktop.
Exercise Solutions - For Loop

For Loops

Please follow the instructions below.

  1. Create an HTML file named for_loop_js.html within the ~/vagrant-lamp/sites/codeup.dev/public folder on your Mac.

  2. Using a for loop and inline JS, write the code to log to the console the following output.

    1
    22
    333
    4444
    55555
    666666
    7777777
    88888888
    999999999
    0000000000
    
    for (var i = 1; i <= 10; i++) {
    			
    	var log = '';
    	for (var j = 1; j <= i; j++) {
    		if (i==10) {
    			log += 0;
    		} else {
    			log += i;
    		}
    	};
    	console.log(log);
    };
  3. Write the JS code to log to the console the multiplication table for a random number between 1 and 10. For instance, if the random number is 7, the console output should look like

    7x1=7
    7x2=14
    7x3=21
    7x4=28
    7x5=35
    7x6=42
    7x7=49
    7x8=56
    7x9=63
    7x10=70
    
    var rando = Math.ceil(Math.random()*10);
    var solution;
    
    for (var i = 1; i <= 10; i++) {
    	
    	solution  = rando * i;
    	console.log(rando+'x'+i+'='+solution);
    };
  4. Using a for loop and the code to generate a random number from the previous lessons, generate 10 random numbers between 20 and 200 and output to the console whether each number is odd or even. For example:

    123 is odd
    80 is even
    24 is even
    199 is odd
    ...
    
    for (var i = 1; i <= 10; i++) {
    	var rando = Math.ceil(Math.random()*(200-20));	
    	var numstate = " is odd"; 
    	if (rando % 2 == 0) {
    		numstate = " is even";
    	};
    	console.log(rando+numstate);
    };
  5. Use inline JavaScript to create a for loop that uses console.log to create the output shown below.

     100
     95
     90
     85
     80
     75
     70
     65
     60
     55
     50
     45
     40
     35
     30
     25
     20
     15
     10
     5
    

    solution:

    for (var i = 100; i > 0; i-=5) {
    	console.log(i);
    };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment