Chapter 2 Exercises

Looping Triangle:

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);
}

Chess Board:

//First attempt:
//console.log(" # # # #\n# # # # \n # # # #\n# # # # \n # # # #\n# # # # \n # # # #\n# # # # \n");

//Second attempt: I needed to check the answer. Could not figure out the if ((x + y) % 2 == 0) step by myself.

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 += " ";
}
else{board += “#”;}
}
board += “\n”;
}
console.log(board);

FizzBuzz

for(var fizzcount = 1; fizzcount <=100; fizzcount++){
if(fizzcount % 5 == 0 && fizzcount % 3 == 0) {
document.write("FizzBuzz
");
}
else if (fizzcount % 5 == 0) {
document.write("Buzz
");
}
else if (fizzcount % 3 == 0) {
document.write("Fizz
");
}
else{
document.write(fizzcount + “
”);
}
}

I intensely had to use the manuals for these, JS makes my head hurt!

Triangle

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);
}

Fizzbuzz

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

Chessboardstrong text

let size_board = 8;
let board = “”;
for(let white = 0; white < size_board; white++) {
for(let black = 0; black < size_board; black++) {
if((white + black) % 2 === 0) {
board += " ";
} else {
board += “#”;
}
}
board += “\n”;
}
console.log(board);

FIZZBUZZ:
for(var num = 1; num <= 100; num++){
if((num%3==0) && (num % 5==0)){
console.log(“FizzBuzz” +""+num);
} else if(num % 3 ==0){
console.log(“Fizz”+" “+num);
} else if(num% 5==0){
console.log(“Buzz”+” "+num);
} else {
console.log(num);
}
}

CHESS BOARD
var size = 8;
var board=" “;
for (var a = 1; a <= size; a++){
for (var b=1; b<=size;b++){
if ((a+b) % 2 == 0){
board += " “;
} else {
board += “#”;
}
}
board +=”\n”;
}
console.log(board)

ps. I tried looking for explanations to the exercise, but once googled, you get the answer straight away…

FizzBuzz

var num_rows = 100;
for(var row = 1; row <= num_rows; row++){
if(row % 15 == 0)
console.log(“FizzBuzz”);
else if(row % 5 == 0)
console.log(“fizz”);
else if(row % 3 == 0)
console.log(“buzz”);
else
console.log(row);
}

Chessboard

var size = 4;
for(var row = 1; row <= size; row++){

    var oddPrint = " #";
    var evenPrint = "# ";

    for(var autosize = 1; autosize<size; autosize++){
      oddPrint += " #"; evenPrint += "# ";
    }


    if(row % 2 == 0)
      console.log(evenPrint);
    else
      console.log(oddPrint);
  }

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

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);
}

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);

These exercises are challenging. I have to go back to Chapter 1 to have an idea how to write these exercises.
I am sure that I am the only one.

3 Likes
  1. Increasing hash by one
    var b="#"
    for (b.length=1; b.length<=7; b=b+"#") {
    document.write(b,"
    ");
    }

  2. fizzbuzz
    var a=1
    var b=3
    var c=5
    for (a=1; a<=100; a++) {
    if (a%b==0 && a%c!=0) {
    document.write(“fizz”,"
    ");
    } else if (a%c==0 && a%b!=0) {
    document.write(“buzz”, “
    ”);
    } else if (a%b==0 && a%c==0) {
    document.write(“fizzbuzz”, “
    ”);
    } else {
    document.write(a,"
    ");
    }
    }

  3. Chequerboard
    var row = 0;
    var cols = 0;

while(row <= 7){
if(row%2 == 0){
document.write(" ");
}
while(cols <= 7) {
document.write( “# “);
cols++;
}
document.write(”
”);
cols = 1;
row++;
}

I Haven’t yet ironed out issues with making the chequerboard a variable number of rows and columns but I am working on it.

Same. Feels really hard for what we’ve learned so far. I was not able to do any of them.

1 Like

Chapter 2 was not that hard for me but Chapter 3 is quite hard. Kinda got stuck and left the course for some time. Gotta get back to it ASAP.

FIZZBUZZ:

        var number = 101;
        for(var count = 1; count < number; count++){
           if (count % 15 == 0){
              console.log("Fizzbuzz");
           }
              else if (count % 3 == 0){
              console.log("Fizz");
           }
           else if (count % 5 == 0){
              console.log("Buzz"); 
           }
           else {
              console.log(count);
        }
     }

CHESSBOARD:

var num = 8;

           for (var row = 1; row <=num; row++){
              var toPrint = ""; 

              for (var col = 1; col <=num; col++){

                 if (row % 2 == 0){

                    if (col % 2 == 0) { 
                       toPrint += " ";
                    }
                       else(toPrint+="#");
                    }
                    else if (col % 2 == 0){
                       toPrint += "#";
                    }
                    else (toPrint+=" ")
              }
           console.log(toPrint);
           }
1 Like

What am I doing wrong? ChessBoard exercise.
var textToDisplay = “#”;

 for(var row = 0; row<8; row=row +1)  {

document.write("

# " + textToDisplay + " " + textToDisplay + " " + textToDisplay + “

”);
}

I did this with help because it is still too complicated for me. But I tried my best!

FIZZBUZZ:

let i = 0;

    while(i < 100){

      i ++;
      if (i % 3 == 0 && i % 5 == 0 ){
        console.log("FizzBuzz")

      }
      else if (i % 5 == 0){
        console.log("Buzz");

      }
      else if (i % 3 == 0){
        console.log("Fizz");

      }
      else {
        console.log(i);
      }

    }

CHESSBOARD:

var size = 8
//Define de variable with empty string:
var board = “”

  for (var y = 0; y < size; y++){
    for (var x = 0; x < size; x++){
      if ((x+y) % 2 == 0){
        board += " ";
      } else {
        board += "#";
      }
    }
    //Add the newline character to create new lines:
    board += "\n";
  }

console.log(board);

This last I got helped from a video on youtube.

2 Likes
  1. Chessboard

    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 += " ";
    else
    board += “#”;
    }
    board += “
    ”;
    }
    document.write(board);

I watched this video for help. was very useful

The solution given by the eloquentjavascript.net does not work.

  1. Fizzbuzz
    Way too difficult for a beginner. I looked at the others results and tried to run these codes…

  2. Triangle
    Same for https://www.youtube.com/watch?v=M4KPaF8Vdvg
    for (var line = “#”; line.length < 8; line += “#”)
    console.log(line);

Hey!

I’ve been looking at your solutions, and I hope you don’t mind me making a few comments…

Apart from the line break (see my comments below), this works, but I think a bit by accident. It could equally work by omitting your initializer b.length = 1 altogether. I think this is because it doesn’t actually do anything:

  • b.length isn’t a valid variable name because it contains a full stop; and

  • your condition b.length <= 7 is checking to see if the string assigned to variable  b  (the variable defined before the for loop) has 7 or less characters (.length being the length property, in this case of a string). This comparison works as the condition for looping, because your “counter” b = b + “#”  is lengthening  b  by  1 x #  at the end of each iteration.

As the  b  variable is being used to count the iterations, I think it should ideally be defined and initialized within the for loop’s parentheses. Your current redundant initializer can simply be replaced with the var b  definition, as follows:

for (var b = "#"; b.length <= 7; b = b + "#") {

}

…which is more like the suggested solution.

The line break in your current code …

…throws a syntax error in my console. The code executes if I put the whole document.write statement on one line, but it produces one single line with spaces. If you want to use document.write() instead of printing to the console, then, to get separate lines, we can amend your loop body as follows:

document.write(b + "<br>");

I was also interested to see, though, that your use of the comma works as an alternative to the  +  operator:

document.write(b, "<br>");

However, using the Google Chrome Console is more straight forward, as each iteration is automatically printed on a separate line:

console.log(b);

You can also make your “counter” more concise with  b += "#"

Here’s an alternative using a while loop, with the variable declared before the loop:

let b = "#";

while (b.length <= 7) {
  console.log(b);
  b += "#";
}

Apart from the same line break issue as with the first exercise, I also couldn’t get this to work because document.write(" "); didn’t add a whitespace at the beginning of my odd numbered lines.
The idea here was to build up one single string, and print the whole chessboard at the end, rather than print each row separately. So, using your same basic program structure, with one while loop nested within another, I’ve come up with the following, which prints to the Google Chrome Console using console.log()

let string = "";
let row = 0;
let cols = 0; 

while (row <= 7) {
  if (row % 2 === 0) {
    string += " ";
  }
  while (cols <= 3) {  // if cols <= 7, rows are twice as long as they should be
    string += "# ";    // because you're adding 2 characters here (#, whitespace)
    cols++;
  }
  string += "\n";
  cols = 0;            // if cols = 1, all subsequent rows have 1 x # too few 
  row++;
}

console.log(string);

Did you solve this final part in the end? If you haven’t here’s a clue:
Having defined the variable size = 8  replace the numbers 7 and 3 (in the while loops’ conditions) with expressions that include size and arithmetic operators, and which define the mathematical relationships between the numbers 7 and 3 and the value of size . You need to ensure that these mathematical expressions evaluate to the correct numbers for the program to work whatever the width x height dimension. You can also make these expressions simpler, by also (i) adjusting the values assigned (and reassigned) to the row and cols variables; and (ii) negating the condition in the if statement.

Let me know if you’d like to see the solution I came up with.

However, having said all that, this code actually gives you a chessboard with an extra square (represented by a whitespace) at the end of every odd row (even though you can’t actually see it). I think there are two main problems which cause this:

  1. The first (outer) while loop treats odd and even rows unequally, by only adding a chessboard square (a whitespace character) to the odd rows.
  2. The second (inner) while loop, adds 2 chessboard squares per iteration (a # character together with a whitespace). I think it’s “cleaner” to only add one character (i.e. one chessboard square) per iteration.

Finally, because we know at the outset how many iterations need to be performed, I think a for loop within another for loop would be more appropriate.

Anyway, I hope that’s helpful. I enjoyed working through your examples :smiley:

Let me know what you think, if you have time, and if you disagree with any of my comments and suggestions — I’m more than happy to stand corrected!


*** UPDATE ****

@rankan — I’ve now found a way to add the whitespace at the beginning of the odd-numbered rows of the chessboard, when using document.write()
I’ve used the HTML entity&ensp;
I got the idea from @javedkhalil’s post here, but I decided to use &ensp; instead of &nbsp; as it creates a wider space. In your code, you should then also replace "# " with "#&ensp;" so that all spaces are of equal width. However, my previous comment — about why we shouldn’t add a # and a whitespace together in the same iteration — means I still think the for loop solution is more appropriate; but now we’ve solved the whitespace issue, we can also use the for loop solution with document.write() as follows:

let chessboard = "";
let size = 8;

for (let row = 1; row <= size; row++) {

  for (let col = 1; col <= size; col++) {
    if ((row + col) % 2 === 0) {
      chessboard += "&ensp";
    } else {
      chessboard += "#";
    }
  }

  chessboard += "<br>";
}

document.write(chessboard);

If you want to know more about HTML entites here are a couple of links:
https://www.w3schools.com/html/html_entities.asp
https://developer.mozilla.org/en-US/docs/Glossary/Entity

Hey!

I’ve been looking at your solutions, and I hope you don’t mind me pointing out that with the chessboard exercise, the idea was to build up a single string for the whole thing, and use new line characters to create the separate rows.

To achieve this, you only need to make the following 3 modifications to your code:

  1. Define your variable toPrint = ""before your outer for loop (instead of within it). This means you will be adding to just one single string throughout the whole program.
  2. Move your console.log() statement to after both for loops (i.e. to the very end of the program) so that you are only printing one string at the end of the whole program, rather than separate strings (for each row of the chessboard) at the end of each iteration of your outer for loop.
  3. Add toPrint += "\n"; at the end of your outer for loop, where you previously had your console.log() statement (i.e. after your inner for loop). The special new line character  \n  creates line breaks, within the same string, for the separate rows.

Just one other thing — if you omit the curly braces in the else statements, then don’t put the statement following the else keyword in parentheses because, even though it still works, it makes them look like conditions (which you only have after   if  or  else if ,  and not after   else ).

I hope that’s helpful :smiley:

The solution given for the chessboard exercise http://eloquentjavascript.net/code/#2.3 works fine for me. Which part couldn’t you get to work? Are you running it with the Google Chrome Console open? Sorry, if that’s pointing out the obvious, but I notice in your code you’re using document.write() to print directly to the web page, whereas console.log() will only print to the console.

In fact, I can’t get your code to work at all using document.write()
Your line break…

…throws a syntax error in my console. I can only achieve the single string with line breaks, and whitespace at the beginning of the odd-numbered rows, by using console.log() and the new line character \n .
Here’s my version using both of these, which is only slightly different to the suggested solution, and also works fine:

let chessboard = "";
let size = 8;

for (let row = 1; row <= size; row++) {

  for (let col = 1; col <= size; col++) {
    if ((row + col) % 2 === 0) {
      chessboard += " ";
    } else {
      chessboard += "#";
    }
  }

  chessboard += "\n";
}

console.log(chessboard);

*** UPDATE ***

@tanja — I’ve now found a way to get your code to work using document.write()
I’ve used the HTML entity&ensp;  to add the whitespace, and the HTML self-closing tag <br> for the line breaks, as follows:

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 += "&ensp;";
    else board += "#";  
  }

  board += "<br>";
}

document.write(board);

I got the idea to use an HTML entity from @javedkhalil’s post here, but I decided to use  &ensp;  instead of  &nbsp;  as it creates a wider space.

  // Exercise 1 - Looping a Triangle
  document.write("<h1>Exercise 1</h1>");
  var strHash = "";
  for(var nextCounter = 0; nextCounter<7; nextCounter++){
    strHash += "#";
    document.write("<h2>" + strHash + "</h2>");

  // Exercise 2 - FizzBuzz
  document.write("<h1>Exercise 2</h1>");
  var strCount = "";
  for(var nextCounter = 1; nextCounter<101; nextCounter++){
    if(nextCounter%3 == 0 && nextCounter%5 == 0){
      strCount = strCount + "FizzBuzz ";
    } else if(nextCounter%3 == 0 && nextCounter%5 > 0){
      strCount = strCount + "Fizz ";
    } else if(nextCounter%3 > 0 && nextCounter%5 == 0){
      strCount = strCount + "Buzz ";
    }else{
      strCount = strCount + nextCounter + " ";
    }
  }
  document.write("<h2>" + strCount + "</h2>");

  // Exercise 3 - Chessboard
  document.write("<h1>Exercise 3 - Chessboard</h1>");
  var myCount = 8;
  var strBoard = "";
  for(var hCount = 1; hCount<myCount+1; hCount++){
    for(var vCount = 1; vCount<myCount+1; vCount++){
      if(hCount%2>0 && strBoard.length%2>0){strBoard+="&nbsp";}
      else if(hCount%2==0 && strBoard.length%2==0){strBoard+="&nbsp";}
      else{strBoard+="#"}
    }
    document.write("<h2>" + strBoard + "</h2>");
    strBoard="";
  }

Looping a triangle

I really like how concise the suggested solution is for this exercise.
It’s interesting how the variable storing the lengthening string of "#"  characters is used to perform 2 functions:

  1. It records the cumulative result to be printed for each iteration; and
  2. It enables the program to count the number of iterations like an abacus, by building up a string with one additional # on completing each iteration. As the variable doesn’t store a number value, the conditional statement has to generate a number value from the “abacus” to compare with the stopping condition. It does this by using the variable’s .length  property to calculate the number of characters in its string.

This means we don’t have to define a separate “result” variable before the loop.

The other thing to note is that, by counting using the length of the string, counting starts at 1 (not 0) with the first # character. This means that, with an output of 7 rows, the stopping condition has to be either <= 7 or < 8 (if you count with number values from 0, you can use < 7 ).


FizzBuzz

I learnt a lot by seeing how my initial solution (before looking at the hints) could be made much more concise by doing the following:

  • Define an empty string variable at the start of the loop’s code block.
      let string = "";
  • Use just 2 consecutive if statements with no corresponding else statements (and so only execute anything if their conditional expressions evaluate to true) to produce 4 alternatives:
      add either (i) "Fizz" or (ii) "Buzz" to the empty string variable if either one or the other of
      the conditions evaluates to true;
      (iii) add both "Fizz" and "Buzz" to the empty string variable if both conditions evaluate
      to true;
      (iv) add nothing to the empty string variable, if both conditions evaluate to false.
      if (number % 3 === 0) string += "Fizz";
      if (number % 5 === 0) string += "Buzz";

   /* I've also learnt how, if you only have one statement in the
      code block, you can omit the curly braces and put the whole
      'if' (or 'else') statement (or 'for' loop) all on one line. */
  • Use a logical OR operator to:
    EITHER
      print the number of the current iteration if the string variable’s value converts to
      the Boolean false (i.e. when it is still an empty string because nothing was added);
    OR
      print whatever the value of the string variable is if it converts to the Boolean true
      (i.e. when it is either "Fizz" or "Buzz" or "FizzBuzz").
      console.log(string || number);

Doing all of the above also means you only need to print to the console once per iteration, instead of 4 times.

This was my (less concise) initial solution (before looking at the hints):

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

Chessboard

An interesting thing to note in the suggested solution is how you can reduce several ifelse statements to just one, by adding the values for the row and column “counter” variables together (like coordinates) in the Boolean expression:

if ((row + column) % 2 === 0) {
  chessboard += " ";
} else {
  chessboard += "#";
}

In fact, I’ve managed to reduce this ifelse statement even further by using a ternary operator, which fits on just one line:

(row + column) % 2 === 0 ? chessboard += " " : chessboard += "#";

This was my (less concise) initial solution (before looking at the hints):

let chessboard = "";
let size = 8;
for (let row = 1; row <= size; row++) {

  for (let col = 1; col <= size; col++) {
    if (row % 2 !== 0) {
      if (col % 2 !== 0) {
        chessboard += " ";
      } else {
        chessboard += "#";
      }
    } else {
      if (col % 2 !== 0 {
        chessboard += "#";
      } else {
        chessboard += " ";
      }
    }
  }

  chessboard += "\n"; 
}
console.log(chessboard);

I realised afterwards that the strict-equality operator  ===  can be used instead of the strict-inequality operator  !==  in the if conditional expressions, if you also invert the positions of the addition-assigned " "   and   "#"   values in both of the nested ifelse statements.

Hi Jonathan,

Thanks very much for the suggestions. I don’t mind at all - I really appreciate it!

Are you studying the course as well? How are you finding it?

I’m not from a coding background so am definitely finding it a challenge, but all good.

Thanks again and all the best.

Jeremy.

1 Like

Fizzbuzz I did, it took me lots of hours. Chessboard I looked at the answers straight away, didn’t want to waist more time. I realized that these excercises are really too hard for somebody born in 1967 and without any IT background. I’ll take smaller steps.