Chapter 2 Exercises

Wow! It took a while!

  1. Triangle: var toPrint =+ “#” ;
    for (let toPrint = “#”; toPrint.length < 8; toPrint += “#”){
    console.log(toPrint)
    }
    It took a while to get how this could go. I finally looked at the solution. I was close.
  2. 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); // I don’t get that || part To insure n doesn’t print?
    }
    I struggled getting how to work the math. I’m not used to % to divide numbers. This too took a while and I had to finally look at the answer after much suffering.
  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);
I would get nothing for a while and then it worked. I checked the answer on this one too. Made some adjustments to get it to work well. I just don’t get the “/n” at the end. To put in a formatting end to a tag? PLease help with this one. I don’t get it.

1 Like

Triangle Loop:

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

FizzBuzz:

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

Chess Board:

var odd= "&nbsp # # # #";
var even= "# # # #"
for(i=0;i<4;i++){
  document.write(odd + "<br>");
  document.write(even + "<br>");
}

“\n” (not “/n”) means “line break”.

For “FizBuzz”, I was a bit puzzled as well by the author’s code too. I think the expression (output || n) makes the console to print either output or n. It checks out the first element (output), and interprets it as FALSE if it has no string, and TRUE if it has some string. So, if it’s true, it gets printed, and if it’s false, it goes to the second element (n), which is always true because it always has a numeric value. Note how output resets to an empty string every time the loop restarts.
If you switch the expression around: (n || output), it will always show n, because it’s always true and there’s no need to evaluate the second part, output.

AAahhhhh. So that’s it.

Thanks SimonB

Saw your profile! I’m a musician too. Play percussion and have been for well a very long time. Good to hear from another musician!

1 Like

Excercise 1

var num_rows = 7;
for(var row = 0; row < num_rows;row ++){

     var toPrint = "#";
     for(var column = 0;column<row;column ++){
       toPrint += "#";

Excercise 2

   for ( var num = 1; num <= 100; num++ )

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

Excercise 3

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

This is not for beginners…I was struggling for two days and did not have much success until I look up the coding. Buzz was little bit easier and I was very close to solve it on my on but the chess was way to hard…

Need more exercises that help you with each of those steps in extra exercises prior to starting
loop a triangle
FizzBuzz
and Chessboard
had no idea where to start

I had to jump right into the solution, to view how the code was written. I wished there was better explanation to each bit of code on each exercise. This way I could’ve gain better perspective on this assignment. I had to read back all the materials from chapter 1 and 2. Currently, I don’t have my own written solution for this exercise, since I was clueless and pathless. Hopefully on the next exercise there’s better explanation.

I’ll try to tell you the logic without giving away the solution:

FizzBuzz:

  • You must make loop that goes through all the numbers from 1 to 100
  • for each number, three things may happen:
    • The number is divisible by 3 (number%3==0)
      • Console shows “Fizz”
    • The number is divisible by 5 (number%5==0)
      • Console Shows “Buzz”
    • None of those cases apply
      • Console shows the number

That’s the first part of the exercise, try to figure out the second (Showing “FizzBuzz” if num%3==0 AND num%5==0)

The Chessboard is a little more complex. Think about it like this:

  • The board has 8 rows and 8 columns.
  • You’ll need one loop for the columns and another for the rows.
  • Ask yourself how to set up the loops so the one that goes through the columns goes through the 8 columns before the one going through the rows advances to the next row.
  • Once you have that figured out, think about what happens on each column:
    • The column is even
      • Console prints a # sign
    • The column is odd
      • Console prints a blank space
  • But… that wouldn’t alternate the position of the # sign between rows!
    • Therefore, something has to happen in the loop that goes through the rows.

See if you can translate that logic into loops and conditional statements. Good luck and patience!

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

for - created the loop, let decleres the variable (let line = “#”; line.length <8; (less that 8] line + “#” (which added the # to the triangle.

I have researched and jumped to the solution to try and work out how the code was wrote. I feel my Syntax is really sloppy so thats where i struggled. But seeing it wrote out i can now explain what is going on a little better.

Const board = document.querySelector(=.board");
const boardletters=document.querySelector(".letters");
const boardnumbers = document.querySelector(".numbers");
let letters=["#"]
let index = 0;
let black=false;
let num = 1; 


for (let i= 0; i < 8; i++)
{ 
     let letter=document.createElement("li");
     letter.textContent = letters [i}i
     boardletters.appendChild(letter);
     let numbers=document.createElement("li);
      numbers.textContent = num++;
      boardnumbers.appendChild(numbers);
}

for (let i = 1; i <=64; i++)
{ 
      const sqaure=document.createElement("div");
      if (black)
{     
square.classList.add("sqaure");
square.classList.add("black");
index++;
black = !black;
} 
elssquare.classList.add("sqaure");
square.classList.add("black");
index++;
black = !black;  }

   board.appendChild(square);
if (index === 8 )
{ 

    black = !black; 
index = 0;

}

Somehwere in this code how can i change the black squares to be # Like the excersize

Thanks guys.  


Looping Triangle:

var num = 7;
for (var row = 0; row < num; row++) {

    var show = "#";

    for (var colunm = 0; colunm < row; colunm++) {
      show += "#";
    }

FizBuzz:

var max = new Array(100); // create an empty array with length 45

for(var i = 0; i < max.length; i++){
  if (i % 3 === 0 && i % 5 === 0) {
  document.write("Fizz Buzz"+ '<br/>');
  }
  else if (i % 3 === 0) {
    document.write("Fizz"+ '<br/>');
  }
  else if (i % 5 === 0) {
    document.write("Buzz"+ '<br/>');
  }
  else {
  document.write( (i) + '<br/>');
  }

}

Chess Board:
I’ve tried to take a different method than most by replicating the lines.

var max = 8;
var show1 = '# # # # ';
var show2 = ' # # # #';
var show3 = "&nbsp";


    for (var row = 0; row < max; row++) {
      if (row % 2 === 0) {
        document.write((show1) + '<br/>');
      }
      else {
      document.write((show3) + (show2) + '<br/>');
      }

}
2 Likes

Greetings @GeoffSwan,
Your Triangle loop and chess board answers are incorrect. Please try again or if you need any help , please look into other answers provided above.

Hi @Monsur, I see that your Looping Triangle example does not have console.log() statement to view your output answer. I believe it should come after the second loop statement. Kindly do edit the answer. :slight_smile:

Happy Learning! :slight_smile:

Hey @Rob_McCourt,
I noticed that there are alot of syntax issues in your code.
You got the first example absolutely right. However, you missed out on a small issue. In the below statement,

You were supposed to rename the “number” variable to “rows” as that’s what you are using in the first loop. so you would have

var rows = 7;
	
	    for (var count = 1; count<=rows; count++){
	      var toPrint = "";
	      var i=0;

The second example is structurally incorrect. In the first "for" loop, you started to use a "else if" condition before having any "if" condition in the first place. This will throw out an error. Other issues that I noticed is you used wrong syntax for "for" loop as shown below

This is incorrect as well, I guess you were going for a for(var i = 0; i < number; i++).
(I removed the two lesser than signs , and changed your
var 1= 0
to
var i =0 )

I know sometimes it can get very hard. But do not worry, I will show you some great explanations to these answers so that you can get reference form it. Read them carefully and also strengthen your syntax basics. If these answers helped you, please drop a like so that other students can take reference too.



If you still have doubts please feel free to reach out or DM.

Happy Learning! :slight_smile:

1 Like

Thanks Abdul, I know it is the Syntax i am having problems with. I had to go back and watch some beginner lessons again and relit that flame inside me pal. I now have a good feeling that if i can understand these two examples and write it on my own, i recon i will progress no problem. But for now. These two and i will get back to you to double check. Can you have a look at Exercises 3 also @Malik please my good man !!!

Hi Monsur

<br what is that?

FizzBuzz

  <script>
      for(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);
      }

  </script>

@Rob_McCourt The ‘’ allows for a line break therefore the next output will be on a new line :+1:

2 Likes
  1. Looping triangle:
    @Malik thank for noticing, it should have read like this:
    var num = 7;
    for (var row = 0; row < num; row++) {

    var show = “#”;

    for (var colunm = 0; colunm < row; colunm++) {
    show += “#”;
    }

console.log(show);

FizBuzz:

var max = new Array(100); // create an empty array with length 45

for(var i = 0; i < max.length; i++){
  if (i % 3 === 0 && i % 5 === 0) {
  document.write("Fizz Buzz"+ '<br/>');
  }
  else if (i % 3 === 0) {
    document.write("Fizz"+ '<br/>');
  }
  else if (i % 5 === 0) {
    document.write("Buzz"+ '<br/>');
  }
  else {
  document.write( (i) + '<br/>');
  }

}

Chess Board:

var max = 8;
var show1 = '# # # # ';
var show2 = ' # # # #';
var show3 = "&nbsp";


    for (var row = 0; row < max; row++) {
      if (row % 2 === 0) {
        document.write((show1) + '<br/>');
      }
      else {
      document.write((show3) + (show2) + '<br/>');
      }

}
1 Like

document.write(“This is the triangle example where we will take the hashmark(#), to create a triangle by increasing the number of #'s for each count.” + “
”)

let result = “”;
for(let counter = 0; counter < 9; counter = counter + 1)
{result = result + “#”; document.write(result + “
”)}

document.write(“For this next example we will take numbers between 1 to 100 and we will print each number except when the number is divisible by 3, we will print Fizzle, and when divisible by 5, we print Bizzle, and when it can be divided by both 3 & 5 we print FizzleBizzle, other wise we just print the number.”+ “
”)

let number =0;
for(let counter = 0; counter < 100; counter = counter + 1)
{number = number + 1;
if(number % 3 == 0 && number % 5 == 0)
{document.write(“FizzleBizzle” + “
”)}
else if(number % 3 == 0){document.write(“Fizzle” + “
”)}
else if(number % 5 == 0){document.write(“Bizzle” + “
”)}
else{document.write(number + “
”)}}

document.write(“For this last example we will print a chess board where we will use the blank space and hash-mark to represent the white and black squares” + “
”)

let string = “# # # # # # # #”;
let string2 = " # # # # # # # #";
for(counter = 1; counter < 9; counter = counter + 1)
{if(counter % 2 == 0){document.write(string+"
")}
else {document.write(string2 + “
”)}}

This last script works inside the console of the browser but will not recognize the empty space in the string2. I could not do anything or find anything that would allow it to print the empty space before printing the hash-mark in string 2.

The first two worked with no problem. But it took me about a hour or two to get the second two work but it has to do with my syntax. Once I got the syntax right it was no problem. Adding the Fizzle and Bizzle combination was simple once I got the Fizzle and Bizzle to work in less than 5 min,

However I also tried to do a .css stylesheet for the output and I had some success but had some major problems. I had to run the script after the body and the end for the script to work. It would not run within the body for some reason. I was trying to make a Header , Navigation, Contents, I wanted to use the Nav bar to activate the script for either program and then run it in the contents section of the page.
All in All it was a lot of fun but a challenge. I think I got in over my head truing to add the .css and Nav to run the program.