Chapter 2 Exercises


#1

Here is the place to discuss the exercises at the end of chapter two.


#2

Triangle Loop

var num_rows = 7;
        for(var row = 0; row < num_rows; row++){
          var toPrint = "#";
          for(var column =0; column<row; column++){
            toPrint += "#";
          }
          document.write(toPrint + "<br>");
        }

FizzBuzz Loop

for (var i=1; i < 10; i++){
          if (i % 15 == 0) document.write("FizzBuzz <br>");
          else if (i % 3 == 0) document.write("Fizz <br>");
          else if (i % 5 == 0) document.write("Buzz <br>");
          else document.write(i + "<br>");
        }

ChessBoard Loop

var size = 8;
var board = "";
for (var y = 0; y < size; y++) {
  for (var x = 0; x < size; x++) {
    if ((x + y) % 2 == 0)
      board += "&nbsp;";
    else
      board += "#";
  }
  board += "<br>";
}
document.write(board);

#3

My solutions
FizzBuzz

for(var count = 1; count <= 100; count++)
{
if (count % 3 == 0)
{
console.log(“Fizz”);
} else if (count % 5 == 0)
{
console.log(“Buzz”);
} else
{
console.log(count);
}
}
ChessBoard
var size = 8;
var board = “”;
var character = false;
for (var row = 0; row < size; row++)
{
for(var column = 0; column < size; column++)
{
if (character == false)
{
board += " ";
character = true;
}
else if (character == true)
{
board += “#”;
character = false;
}
}
board += “\n”;
character = !character;
}
console.log(board);


#4

Triangle Loop

for(var i = 0; i < 7; i++)
{
var toprint= ‘#’;
for(var j = 0; j < i ; j++)
{
toprint = toprint + ‘#’;
}
console.log(toprint);
}

Triangle Loop Reverse

for(var i = 0; i <= 6; i++)
{
var toprint= ‘#’;

for(var j = 0; j < 6 -i; j++)
  {
      toprint = toprint + '#';
  }

document.write("<h2>" + toprint + "</h2>");

}

FizzBuzz Loop

for(var i = 1; i <= 100; i ++)
{
if(i % 3 == 0 && i % 5 == 0){console.log(‘FizzBuzzzzzzzzzzz’);}
else if(i % 5 == 0 && i % 3 !=0){console.log(‘Buzz’);}
else if(i % 3 == 0){console.log(‘Fizz’);}
else {console.log(i);}

}

ChessBoard

var nbr = 8;

for(var ligne = 1; ligne <= nbr; ligne ++)
{
var toprint_I= ‘#’;
var toprint_P= ’ ‘;
var tot=’’;

    if(ligne%2 != 0){ for(var i = 0; i < nbr/2; i ++){tot += toprint_I;tot +=toprint_P;}
                    /*if(nbr%2 != 0){tot = tot - "#";}*/
                    console.log(tot);
                    }
    else if(ligne%2 == 0){for(var i = 0; i < nbr/2; i ++){tot += toprint_P; tot+=toprint_I;} console.log(tot)

    }

}

#5

Looping a Triangle

	<script>
	
	    var number = 7;
	
	    for (var count = 1; count<=rows; count++){
	      var toPrint = "";
	      var i=0;
	      
	      while(i<count){
	        toPrint += "#";
	        i++;
	      }
	      console.log (toPrint);
	    }
	
	</script>

FizzBuzz

	<script>
	    
	    for (i=1; i<=100; i++){
	
	      if (i%3==0){
	
	        if(i%5==0){
	          //If it is both print FizzBuzz
	          console.log ("FizzBuzz");
	        }
	
	        else {
	        //If it is divisible by 3 than do this code
	        console.log ("Fizz");
	        }
	
	      }
	      else if (i%5==0){
	        //If it is divisible by 5 and not 3 do this code
	        console.log ("Buzz");
	      }
	      else (console.log (i));
	
	
	    }

	</script>

Chessboard

	<script>
	
	    for (var row=1; row<=8; row++){
	      var toPrint = "";
	
	      for (var col=1; col<=8; col++){
	
	        if (row%2==0){
	            //If the row is even start with a black square
	            if (col%2==0){
	              //If the column is even, white square...
	              toPrint+=" ";
	            }
	            //If only the row is even, black square...
	            else(toPrint+="#");
	        }
	        //If the row is odd start with a white square
	        else if (col%2==0){
	          //If the column is even, black square...
	          toPrint+="#";
	        }
	        else (toPrint+=" ");
	        //If only the row is even, white square...
	      }
	
	      console.log (toPrint);
	      //Print the line to the console

	    }
	</script>

#6

Chapter 2 Exercises

My initial answers differed from the following answers, and there are many ways to do things, but the methods described below are the cleanes and simplest answers and are worth discussion.

  1. Looping a triangle:
    for (statement 1; statement 2; statement 3) {code block to be executed}
    

    The basic for loop takes 3 input statements. The first is executed before the loop (the code block) starts, the second defines the condition for running the loop and the third is executed each time after the loop has been executed.

    The simplest solution to the looping problem is a single line for-loop.

    for (var line = "#"; line.length < 8; line += "#") console.log(line);
    

    Inside the first statement (executed before the for loop loop ), a string variable called length is created with a single, (#). This will be the first value used by the code block (console.log()). By using the string length property (.length) JavaScript we limit the possible string length to less than 8, (which means it will reach maximum 7). Finally we add in statement 3, to be executed after each iteration, we envoke and addition assignment operator (+=) to add an additional # to line variable.

  2. FizzBuzz
    for (let n = 1; n <= 100; n++) {
    let output = "";
    if (n % 3 == 0) output += "Fizz";
    if (n % 5 == 0) output += "Buzz";
    console.log(output || n);}
    

    This solution condenses to the simplest level using a for-loop containing if-statements. What makes it simple is the use of the or-operator in the last line. It gives the ability to log the output or if there is no output, log the number. The biggest thing to take away are that a string of length zero returns a false boolean and that a let binding created within a loop’s code block is reset after each iteration.

  3. Chessboard

    let size = 8;
    let board = "";
    for (let y = 0; y < size; y++) {
       for (let x = 0; x < size; x++) {
           if ((x + y) % 2 == 0) {board += " ";} 
           else {board += "#";}
           }
       board += "\n";}
    console.log(board);
    

    In this problem you are told will have a checkerboard of 8 spaces in each direction. The initial conditions set are a variable called size equal to 8 and a varibale called board equal to a string of length zero. We examine the code and see that the for loop in the x-axis (same line) is nested inside the y-axis loop. Both of the axis are constrained by the board size, and after each iteration the y-axis loop adds a line break to the character in board, thus pushing the next iteration of the x-axis loop onto the next line. The way each space is marked depends on the mathematics behind if that space is even or it is odd and having it applied with a simple if-else statement. .


#7

Not easy for a beginner. I’ll have to start with more of a baby step method. This was a little too much at once for me.

Looping a Triangle
for (let line = “#”; line.length < 8; line += “#”)
console.log(line);

FIZZ BUZZ
for (let n = 1; n <= 100; n++) {
let output = “”;
if (n % 3 == 0) output += “Fizz”;
if (n % 5 == 0) output += “Buzz”;
console.log(output || n);
}

CheeseBoard Loop
let size = 8;

let board = “”;

for (let y = 0; y < size; y++) {
for (let x = 0; x < size; x++) {
if ((x + y) % 2 == 0) {
board += " ";
} else {
board += “#”;
}
}
board += “\n”;
}

console.log(board);


#8
Course Exercises

Pyramid

var numRows = 7; for(var row = 0; row < numRows; row++){ var pyramid = "#";
    for(var column = 0; column < row; column++){
      pyramid += "#";
    }
    console.log(pyramid)
  }
</script>

FIZZBUZZ

var count = 1 var f = "FIZZ"; var b = "BUZZ";
  for(list = 1; count < 100; list++){
    if(list % 5 == 0 && list % 3 == 0) console.log(f+b);
    else if(list % 3 == 0) console.log(f);
    else if(list % 5 == 0) console.log(b);

      else console.log(count);
    count++
  }

</script>

Chessboard

var wdt = 8; var hgt = 8; var board = " "; for(var col = 1; col <= wdt; col++) { for(var row = 1; row <= hgt; row++) { if((col + row) % 2 == 0) board += " "; else board += "#"; } board += "\n" } console.log(board);
</script>

#9

I like solving problems with functions :)))

Triangle

function triangle(rows) {
  let hash = '#';
  for(let i = 0; i < rows; i++) {
    
    console.log(hash);
    hash += '#';
  }
}

const output = triangle(5); //triangle will have 5 rows
console.log(output);

FizzBuzz

function fizzBuzz(num) {
  for(let i = 1; i <= num; i++) {
    if(i % 3 === 0 && i % 5 === 0) {
      console.log('FizzBuzz');
    } else if(i % 3 === 0) {
      console.log('Fizz');
    } else if(i % 5 === 0) {
      console.log('Buzz');
    } else {
      console.log(i);
    }
  }
}

const output = fizzBuzz(100);
console.log(output);

ChessBoard

function chessBoard(rows, columns) {
  const topArr1 = [];
  const topArr2 = [];

  for(let i = 0; i < rows; i++) {
    if(i % 2 === 0) {
      topArr1.push(' ');
      topArr2.push('#');
    } else {
      topArr1.push('#');
      topArr2.push(' ')
    }
  }

  for(let i = 0; i < columns; i++) {
    if(i % 2 === 1) {
      console.log(topArr1.join(''));
    } else {
      console.log(topArr2.join(''));
    }
  }
}



const output = chessBoard(8, 8);
// Experiment with chessBoard(2, 5) or chessBoard(15, 3) x))) 
console.log(output);

#10

1. TRIANGLE

Remembering from the book...(page 32)
for (let number = 0; number <= 12; number = number + 2)
{console.log(number); } // → 0 // → 2 // … etcetera
Do you notice how similar that problem is to ours? The only differences are we want the loop to stop at 7 and our BINDING NAME equals "#" instead of 0, it's a string instead of integer and we are incrementing by 1, not 2. So lets call the word number tictactoe instead of number. Now let's try with our replaced values.
for(let tictactoe ="#"; ticktactoe <=7; tictactoe=tictactoe+"#";
{ console.log(tictactoe)};
Nothing happens, but why? Luckily the book gives up a big hint.
It may be useful to know that you can find the length of a string by writing .length after it.
let abc = "abc";
console.log(abc.length);
// → 3
Is tictatoe a string? Yes it is. Now we can say
for(let tictactoe ="#"; ticktactoe.length<=7; tictactoe=tictactoe+"#";
{ console.log(tictactoe)};

2. FIZZBUZZ

Write a program that uses console.log to print all the numbers from 1 to 100. We can use page 32 information again making a few changes.
for (let number = 0; number <= 100; number = number + 1)
{console.log(number); }
// → 0
// → 2
// … etcetera

FYI: 1.01, .67 is number so that could be trick question but for this case let’s just increment by 1. And, it works. Speaking of tricks, they do trick us, not so easy. Now they want…For numbers divisible by 3, print “Fizz” instead of the
number, and for numbers divisible by 5 (and not 3), print “Buzz” instead.

for (let number = 0; number <= 100; number = number + 1)
{console.log(number);

}
For numbers divisible by 3,For numbers divisible by 5

for(number/3number%3==0);{console.log("Fizz");}
for(number/5number%5==0);{console.log("Buzz");
If, if, else...
for (let number = 1; number <= 100; number = number + 1) {
if (number%3==0) {
console.log("Fizz")}
if (number%5==0) {
console.log("Buzz")}
else {
console.log(number); }
// IT PRINTS CORRECTLY!
}

CHESSBOARD

(Note: I wasn't proud of my answer. I needed a lot of help to complete it and it's sloppy.)
Write a program that creates a string that represents an 8×8 grid, using newline characters to separate lines. At each position of the grid there is either a space or a "#" character. The characters should form a chessboard.

Let's think about each line and what is it is really saying.
Write a program function() that creates a string=var s that represents an 8×8 grid =8, using newline characters to separate lines for( ){ }.

var s =8;
for (let var a=0; a < s ; a++){ console.log(a);}

At each position of the grid there is either function Odd(num) {return num %2;} a space varspace = " “;
or a “#” character. var hashtag =” # ";


var spacetag=" # "
var space=" ";

The characters should form a chessboard.

var s =8;
var spacetag = " # ";
function Odd(num) {return num % 2;} // I had to search google for the that.
for(let a=0; a < s; a++){
if(Odd(a)){
console.log(spacetag+spacetag+spacetag+spacetag);}
else{
console.log(" "+spacetag+spacetag+spacetag+spacetag);}
}

#11

Great examples so far.
Just for fun, I thought it might be worth mentioning how NOT to write code.

One of the mantras of coding is “Keep It Super Simple”.
However, that does not mean that your code has to be so refined that it all fits on a single line and resembles an algebraic formula.

Case in point: the ‘Fizz/Buzz’ exercise.

for (var i = 1; i <= 100; i++) console.log((i % 3 == 0) ? “Fizz” : ((i % 5 == 0) ? “Buzz” : “”));

Yay, it all fits on one line! Aren’t I clever?
Well no.

It is extremely hard for another developer to read and to figure out what the code does.
Machines don’t care, but people do.

Remember, that some poor blighter is going to have to extend or debug your code at some point in the future (that could even be you, weeks or months after you’ve forgotten what the logic is intended to do). And the above code will mean that someone has to most likely refactor it just so they can understand it.

Be nice to other developers and write readable code.
</soapbox>


#12

Here is a solution for Fizzbuzz:
var max=100;
for(i = 1; i<=max; i++){
if(i%5==0 && i%3==0){
console.log(“FizzBuzz”);
continue;
}
if(i%3==0){
console.log(“Fizz”);
continue;
}
if(i%5==0){
console.log(“Buzz”);
continue;
}
console.log(i)
}


#13

Here is a really simple solution for the Chessboard.
//Exercise Chessboard
var chess=8;
var board1="# # # #";
var board2=" # # # #";
for(i = 1; i<=chess; i+=2){
console.log(board2+"\n");
console.log(board1+"\n");
}


#14

Triangle

               for (let row = 0; row < 7; row++) {
			let toPrint ="#";
			
			for (let col = 0; col < row; col++) {
				toPrint += "#";
			}
			console.log(toPrint);
		}

FizzBuzz

		for (let i = 1; i <= 100; i++) {
			if ((i % 3 == 0) && (i % 5 == 0)) {
				console.log("FizzBuzz");
			} else if (i % 3 == 0) {
				console.log("Fizz");
			} else if (i % 5 == 0) {
				console.log("Buzz");
			} else {
				console.log(i);
			}
		}

ChessBoard

		let size = 8;
		let toPrint = "";
		for (let row = 0; row < size; row++) {
		   for (let col = 0; col < size; col++) {
			   if ((row + col) % 2 == 0) {
					toPrint += " ";
				} else {
					toPrint += "#";
				}
			}
		   toPrint += "\n";
		}
		console.log(toPrint);

#15

I’ve made things a little bit different than others but the results are the same, i never used a double FOR:

Triangle Loop:

  var str1 = "#";
  var str2 = "";
  for (var j = 0; j < 7; j++) {
       str2 = str2 + str1;
      document.write("<h5>"+ str2 +"</h5>");
  }

FizzBuzz

  for (var k = 1; k < 101; k++) {
    if ((k % 3 == 0) && (k % 5 == 0)) {
        document.write("<h5>FizzBuzz - </h5>");
    }
    else if (k % 3 == 0) {
        document.write("<h5>Fizz - </h5>");
    }
    else if (k % 5 == 0) {
        document.write("<h5>Buzz - </h5>");
    }else {
      document.write("<h5>"+ k +" - </h5>");
    }
  }

Chessboard

  var filasColumnas = 8;
  strChess1 = "&nbsp;#";
  strChess2 = "#&nbsp;";
  strChess3 = "";
  strChess4 = "";
  for (var l = 0; l < filasColumnas; l++) {
    strChess3 = strChess3 + strChess1;
    strChess4 = strChess4 + strChess2;
  }

  for (var m = 1; m <= filasColumnas; m++) {
    if (m % 2 == 0) {
      document.write("<h5>"+ strChess3 +"</h5>");
    }else {
      document.write("<h5>"+ strChess4 +"</h5>");
    }
  }

#16

Hey Vince ,nice I was thinking about doing the same!! jeje but then I read the last part of the exercise where they asked to: “define a binding size = 8 and change the program so that it works for any size,”. However good thinking, keep it up!


#17

Triangle

for (row = '#'; row.length <= 7; row += '#')
  console.log(row);

Plain and simple. At first I also wanted to use two for loops with integers like Ivan, but the hint on .length gave the clue to the shortest solution.

FizzBuzz

for (var i=1; i<=100; i++) {
  var isMultipleOf3 = i % 3 == 0;
  var isMultipleOf5 = i % 5 == 0;
  
  if (multipleOf3 && multipleOf5)
    console.log("FizzBuzz")
  else if (multipleOf3)
    console.log("Fizz");
  else if (multipleOf5)
    console.log("Buzz");
  else
    console.log(i);
}

This is possible much shorter, the books solution only uses two if statements (and no else) and the || operator in a clever way.

Chessboard

const size = 8;

var board = '';
for (var row = 0; row < size; row++) {
  var isDark = (row % 2 == 1); // every odd row starts with dark square
  for (var col = 0; col < size; col++) {
    board += (isDark ? '#' : ' ');
    isDark = !isDark;
  }
  board += '\n';
}

console.log(board);

In comparison to the books solution this one uses the modulo operator only once per row to determine the starting color and from then only alternates the color by applying NOT (!) to the boolean value isDark. For the concatenation of the next square the ternary operator (? :) is used. Alternating all over the board would only work for odd values of size. The books solution, also proposed here by some fellows, is probably more readable.


#18

Only one loop is needed for triangle exercise if you use concatenation:

var numRows = 7;
var rowString = “#”;
for(var row=0; row<numRows; row++){
console.log(rowString);
rowString = rowString + “#”;
}


#19

Triangle:

let rowNum = 7;
for(var row =0;row<rowNum;row++){
  let hashes = "#";
  for (var hash=0; hash<row; hash++){
    hashes+="#";
  }
  console.log(toPrint);
}

FizzBuzz

for(i=1;i<101;i++){
  let num = i;
  if(num%3==0){
    console.log("Fizz");
  }
  else if(num%5==0){
    console.log("Buzz");
  }
  else {
    console.log(num);
  }
}

Chessboard:
I thought this exercise required a variable for both row and column, that’s why my code looks different from everyone elses:

let row = 16;
let col = 16;
let toPrint = "";

  for(i=0;i<row;i++){
    for(j=0;j<col;j++){
      if(i%2==0){
        if(j%2==0){
          toPrint+=" "
        }
        else {
          toPrint+="#"
        }
      }
      else {
        if(j%2==1){
          toPrint+=" "
        }
        else {
          toPrint+="#"
        }
      }
    }
    toPrint+="\n";
  }
console.log(toPrint);

#20

var num_rows = 7;
for(var row = 0;) row < num_rows; row++){
var toPrint = “#”;
for(var column = 0; column<row; column++){
toPrint += “#”;
}
console.log(toPrint);
}
I’m not sure if I’m doing this correctly, it will not display on the site. What am I doing wrong?