Chapter 2 Exercises

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

1 Like

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.

1 Like

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.

1 Like

Hello guys, can you have a look of my triangle please? I think I did it without using two loops.

TRIANGLE

var toPrint ="#";
for (var rowCounter = 0; rowCounter < 7; rowCounter++){

      console.log(toPrint);
      toPrint+="#";
    }

FizzBuzz

var num = 1;

    for(var i=0;i<100;i++){

      if(num%3 == 0){
                    
        if(num%5 == 0){
          
          console.log("FizzBuzz");
        }
        
        console.log("Fizz");            
      } else {
                    
        if(num%5 == 0){         
               
          console.log("Buzz");                          
        }                        
      }
      if(num%3 != 0 && num%5 != 0){     
               
        console.log(num);            
      }                    
      num++;                    
    }

Chess Board

var size;
var board = “”;

size = prompt(“Size?”);

for(var x = 0; x < size; x++){

for(var y=0; y < size; y++){

   	if((x+y)%2 == 0) {

       	board += " ";

           } else {

           board += "#";

           }
      }

  board +="\n"; 

}

console.log(board);

Lol, they’re also a challenge for people born past your birthday, trust me!!

My FizzBuss
for (let number = 0; number <= 99; number = number + 1)
{
var hitt = 0;
if (number % 3 == 0 && number % 5 != 0 )
{
console.log(number + ’ Fizz’);
hitt = 1
}
if (number % 5 == 0 && number & 3 != 0)
{
console.log(number + ’ Buzz’);
hitt = 1
}
if (number % 5 == 0 && number % 3 == 0 )
{
console.log( number +’ FIZZ Buzz’);
hitt = 1
}
if (hitt == 0)
{
newFunction(number);
}

}
function newFunction(number) {
console.log(number);
}

My Chessboard
for (let rows = 1; rows<= 8; rows = rows + 1)

{

var hstring =’’

for (let col = 1; col <= 4; col = col + 1)

{

if (rows % 2 == 0)

{

hstring = hstring + '# ’

}

if (rows % 2 != 0)

{

hstring = hstring + ’ #’

}

}

console.log(hstring ) ;

}

FizzBuzz

var x=0;
for(x=1;x<=100;x++)
{
if(x%3==0 && x%5!=0)
console.log(“Fizz”);
else if (x%3!=0 && x%5==0)
console.log(“Bizz”);
else if (x%3==0 && x%5==0)
console.log(“FizzBizz”);
else
console.log(x);
}

ChessBoard
var x=0;
for(x=0;x<8;x++)
{
if(x%2==0)
console.log(" # # # #");
else
console.log("# # # # ");
}

Yeh, your code for the triangle works fine. You don’t actually need two loops for this one :wink:

Thanks a lot for checking :slight_smile:

1 Like

Triangle
let num_rows = 7
for (rows=0;rows<num_rows;rows+=1){
let toPrint = “#”;
for (columns=0;columns<rows;columns+=1){
toPrint += “#”;
}
console.log(toPrint);
}
Fizzbuzz
for (homework2=1;homework2<=100;homework2+= 1){
if(homework2%3==0 && homework2%5==0) {
console.log(“Fizzbuzz”);
}
else if (homework2%5==0) {
console.log(“Buzz”);
}
else if (homework2%3==0) {
console.log(“Fizz”);
}
else{
console.log(homework2);
}
}
Chessboard
let size = 8;
let board = “”;
for(y=0;y<size;y+= 1){
for(x=0;x<size;x+= 1){
if((x+y)%2==0){
board +=" ";
}
else{
board += “#”;
}
}
board+= “\n”;

}console.log(board);

FIZZBUZZ:

for (var i=1; i < 101; i++){

          if(i % 15==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 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);

FIZZBUZZ:

var number = 0;
for (i=0; i<100; i++){
number++;
if (number % 3 == 0 && number % 5 == 0) {
console.log(“FIZZ and BUZZ”);
} else if (number % 3 == 0) {
console.log(“FIZZ”);
} else if (number % 5 == 0) {
console.log(“BUZZ”);
} else {
console.log(number);
}
};

CHESS BOARD:

var b = " ";
var h = “#”;
var c1 = b + h + b + h + b + h + b + h;
var c2 = h + b + h + b + h + b + h + b;

for (i=1; i<=8; i++){
  if (i % 2 != 0) {
    console.log(c1);
  } else {
    console.log(c2);
}

};

I know, I know: the size of the chess board cannot be scaled…

<!DOCTYPE html>
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>searchengine</title>
  </head>
  <body>
    <script>
      document.write("<h1>"+"Triangle"+"</h1></br>");
      var numberofrows=7;
      var toprint="#";
      for (var r=0;r<numberofrows;r++){
        var toprint="#";
        for (var pointer=0;pointer<r;pointer++){
          toprint+="#";
        }
      document.write(toprint+"</br>");
      }
      document.write("<h1>"+"Fizzbuzz"+"</h1></br>");
      for(var i=1;i<100;i++){
        if (i%3==0&&i%5==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>");
      }
      document.write("<h1>"+"Checkboard"+"</h1></br>");
      var text1="&nbsp # # # #", text2="# # # #";
      for (var i=0;i<8;i++) {
        if (i%2) document.write(text2+"</br>");
          else document.write(text1+"</br>");
      }

    </script>

  </body>
</html>

Triangle:

<script type="text/javascript">

var print = "#";
for (var i = 1; i<8; i += 1) {



if(i>1){
  print = print + "#";
  console.log(print);
}
else(console.log(print))
}



</script>

Fizzbuzz:

<script type="text/javascript">

for(i=1; i<=100; i++){

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

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

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

else {
  console.log(i);
}

}

</script>

Chessboard:

<script type="text/javascript">

var height= 5;

for(var row=1; row < height; row++){

  var even = " # # # #"
  var uneven = "# # # # "
console.log(even);
console.log(uneven);

}



</script>
1 Like