Chapter 2 Exercises

fizzbuzz

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

Chessboard

var boardsize = 8;

var chessboard = “”;

for (var q = 0; q < boardsize; q++) {
for (var k = 0; k < boardsize; k++) {
if ((k + q) % 2 == 0)
chessboard += " ";
else
chessboard += “#”;
}
chessboard += “\n”;
}

console.log(chessboard);

Thank you for answering. May I know why the second example will not produce the correct answer? It seems that i got the

####### part right but there’s an additional part to my answer which is
“########”. Could you kindly explain the logic behind this? Thank you very much sir.

For the first example, I changed the position of var pyramid ="#"; to the first line rather than putting it after the for(var row = 0; row < 7; row++){ line, and the answer changes completely too. Do you mind explaining to me the logic behind this? Again thank you very much sir.

question 2:

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

For the first two exercises, I wrote them in Atom, and wanted them displayed on the practice webpage. I found chessboard very confusing, and ended up having to look up the answer.

Looping a Triangle:

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

FizzBuzz:

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

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 += "\n"
  }
  console.log(board)
2 Likes

Looping a triangle:
var num_rows = 8;
for(var row = 0; row < num_rows; row++){
var toPrint = “#”;
for(var column =0; column<row; column++){
toPrint += “#”;
}
document.write(toPrint + “
”);
}
FizzBuzz Loop


My FizzBuzz does not work, can somebody help? I do not know what I am doing wrong

@Mroman remove the jquery link(src = https://ajax…) from script tag then It should work. you are not using it.

Happy coding :grinning:,
Abel S.

2 Likes

Many thanks, it works

1 Like

1.Triangle
for(i="#";i.length<8;i+="#"){
console.log(i);
}
2.FizzBuzzfor(a=1;a<=100;a++){
if (a%3==0){
console.log(“Fizz”);}
if (a%5==0){console.log(“Buzz”);}
console.log(a)
}
3.Chessboard
for(y=0;y<=8;y++){
if(y%2!=0) {console.log(" “+”#"+" “+”#"+" “+”#"+" “+”#");}
if(y%2==0){console.log("#"+" “+”#"+" “+”#"+" “+”#"+" ");}
}

I may have over thought this but I figured that we are needed to convert to JS to keep developing our web site rather than just executing console .log.

Also I tried to make the Chess Board look more like a Chess Board…

Great Exercise :wink:

Looping a Triangle

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 + “
”);
}

  1. Fizz Buzz Loop

for (var i = 1; i<31; 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+”
”);
}

  1. Chess Board

var rows = 8;
var columns = “”;
for (var y = 0; y < rows; y++) {
for (var x =- 7; x < rows; x++) {
if ((x + y) % 2 == 0)
columns += " ";
else
columns += “#”;
}
columns += “
”;
}
document.write(columns);

Hi @Ziheng,
I understand what you mean. In the code below ,

The Chrome console always tries to print the evaluation of a statement. In addition to the output of console.log() calls, the console also displays the value of the last expression executed in the code you run there. Thus, the extra "########” is NOT from the console.log() that you wrote. It is the general outcome of an expression. The expression, in this case, is the for loop, and the outcome is the variable “x”.

If you write the same thing in an actual script file and run it on the browser you won’t see such a behaviour.

Now, for the below code,

When you declare the pyramid variable all the way on the top, it becomes a global variable. That mean when the second loop i.e. for(var column = 0; column < row; column++) finishes , the pyramid variable doesn’t get resetted. It carries the old value, now if you add the string, it carries the previous string value and adds the new loop string, that’s why you see unexpected long strings.

When you declare the pyramid variable just below for(var row = 0; row < 7; row++) , it resets (technically re decalres ) itself when the second loop for(var column = 0; column < row; column++) finishes. Thus, in this case, you see the expected answer.

This exercise really take a toll to your imagination. Feel free to play around and discover the intricacies of the language. You will have fun :smiley:

Hope this clarifies your doubt.

Happy Learning! :slight_smile:

1 Like

Here we go…

Background

I solved the first two (before watching Ivan's solution to the first one) and was feeling great about myself. The third one kicked my rear, so much that after two + hours I ended up looking at the solution from the text book. In my defense, I thought there was a blank line between each row from the looks of the book, so was over-complicating. Regardless, having the answer definitely makes sense, all about the relationship between the y and x variables > if both are even (thus divisible by 2 so % 2 == 0) then it's a " ", if one is odd, then "#". The \n variable threw me for a curve.

If anyone can comment, my solutions for 1 and 2 are both different. I know there are many ways to get to the right answer, as proved by Ivan's solution to 1 being different than the book's. But still would help to get feedback on which is preferred or where I should adjust my thinking.

Overall this has been a great learning experience - messing with the code myself and trying to figure things out.

Looping a Triangle

My Solution

var hashtag = "#"

          while (hashtag.length<=7) {
            console.log(hashtag);

            hashtag += "#";

          }

FizzBuzz

My Solution step 1

var number = 1
        while (number<=100) {
            if ( number % 3 == 0){
              console.log("Fizz")
            } else if
              ( number % 5 == 0){
                console.log("Buzz")
              } else {console.log(number)}
              number ++;
            }

My Solution step 2 (yes, tried up to 10000 for fun)

  var number = 1

        while (number<=10000) {
              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)}
              number ++;
            } 

Chessboard

Book's solution - this kicked my behind after 2+ hours

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

My chessboard is not working…Could you help me?

To be honest, I wasn’t able to solve any of the exercises without looking at the answer. Once I checked the answer, I was able to understand the logic behind it. However, I don’t understand that x+y part on the chessboard exercise. Can anyone clarify?
Thanks

Not that I figured out the chessboard on my own (spent over two hours on that one), but, the logic has to do with the relationship between x and y.

If you outline all the coordinates, you’ll see that anytime x and y are both even numbers or odd numbers, it’s a #, while anytime x and y are a mix of even and odd, it’s a " ". In other words, if (x + y) % 2 == 0, then you’ll have a #, while if (x + y) % 2 != 0, then it’s a " ".

This was tough, but helps drawing it out and labeling the coordinates to see the relationships between x and y.

edit: the other way around, but you get the idea

2 Likes

It was really frustrating but educational to struggle with these exercises for me as a complete newbie. Exercise one and two were fine after some headache and some external reading about the syntax of different expressions. It was the third exercise that really took a while to grasp for me. I’ve been returning to it for three days now :joy: since I felt that I had to understand it completely before continuing. I’ll post my final code:

var size = 10, board = “”

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

  document.write(board);

I first got it to write it in the console, but when I wanted to make it work “on the website”, so to speak, it looked nothing like what I aimed for. I found (right or wrong) that the “\n”-expression only worked in the console so I changed it to “< br >” and I got it to work. And where it reads board += “&nbsp” I first used board += " ", but that only worked in the console for some reason. I got no checked chessboard, only straight rows of “#” and " ". But the &nbsp solved it for me.

One thing I didn’t understand in the beginning was why the y variable resets for every loop of x. I guess that’s just the way it works since the y-loop is inside the x-loop? New x-loop mean that everything in the {} is back to the original values.

I feel that I’ve actually learned a lot from struggling to understand the loops inside loops and difference between the console and the “web-page”.

1 Like

Thank you @Malik , i get the first part now. However, for the second part, I
still don’t quite get what you mean by

Could you maybe explain this to me with the use of the equation/ example? Your help would be deeply appreciated. :smiley:

1 Like

FizzBuzz

for (i=1; i<=100; i++){
let output=""
if(i%5==0){output+=“Buzz”}
if(i%3==0){output+=“Fizz”}
document.write(output || i)
}

for some reason this won’t output the entries in a column, just writes them in a horizontal line. Where would i put a break element in this code to make each i value place on a new line?

//FizzBuzz solution

for (let number=0; 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 if { console.log(number);

}
}

Oh my God ,this was difficult to figured it out. I spent a lot of time to find a solution.
I will post the code for the Chessboard hopefully soon.

2 Likes

ok this seems to have worked

1 Like

Looping Triangle

FizzBuzz

Chessboard

1 Like