Chapter 2 Exercises

<script>

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

  if(i%5==0 && i%3==0){
    document.write("<p> Fizzbuzz </p>");
  }
  else if(i%3==0){
    document.write("<p> Fizz </p>");
  }
  else if(i%5==0){
    document.write("<p> Buzz </p>");
  }
  else {
     document.write("<p> " + i + " </p>");
   }

}




</script>
<script>
var textRow="\xa0";
var SIZE=16;
for(var row=0; row<SIZE; row++){

  for(var col=0; col<SIZE; col++){

      if(row%2==0 && col%2==0){
        textRow+="\xa0";
      }
      else if(row%2==0 && col%2!=0){
        textRow+="#";
      }
      else if(row%2!=0 && col%2==0){
        textRow+="#";
      }
      else{
        textRow+="\xa0";
      }

  }

  document.write("<h3>" + textRow + "</h3>");
  textRow="\xa0";

}






</script>

Hey, nice try! Just one thing a noticed, in your code about fizz and buzz! Because you start with an if condition with num % 3==0, this would been if this is true the other conditions would not be evalutated. Since num % 3==0 always are true for all the cases of num % 15==0 the else if condtion for else if(num % 15==0) would never be invoked.

Take the number 15. If the number is 15, the first condition is true, thereby the code would write fizz! But we want it to write fizzbuzz at 15. If you instead start with a if(num % 15==0){…} this would be invoked every time the number could be diveded by 15, and then have else if(number% 3==0) after 15.

Hope it give at least some meaning.

Well, after I did my code, I looked at the solution and that erased what I wrote. :slight_smile: Didn’t think we’d paste it here.

Triangle
Mine was a bit different from the other examples in that I created a string “#################” and then I printed out the substring based on the length/position. console.log(mystring.substring(0, mylenght)

FizzBizz
I wanted to try and be a little more elegant and not do 3 conditionals. Instead of doing (i % 15) I basically did
if (i % 3){ string += “Fizz”;}
if (i % 5){ string += “Buzz”;}

So it still printed FizzBizz when both matched.
Also, I added the line number to the front of the line.
Couldn’t figure out how to easily format the width of the number so I separated the number and the rest of the line with a tab.

Board
Guess I misread the problem (based on the solution). I thought I should be able to change both width and height. The solution identified each square by it height and width position, I wrote my code a line a time and just specified with (i % 2) whether it started with a black or a white square.

TRIANGLE
I came up with a shorter and simpler solution than Ivan’s by using a single variable and the .length property, following the hint given on the book. Needless to say, I’m very happy with myself. :smiley:

  for (var tic = "#"; tic.length <=7; tic += "#"){
  console.log(tic);
  }

FIZZBUZZ (iteration 1)

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

FIZZBUZZ (iteration 2)

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

CHESS BOARD

After struggling with this one for days and days, i saw @iris 's brilliant answer and learned from it tremendously (thanks, @iris !). I modified it slightly, changing the variable names to make it more obvious for myself and others, tweaked the counters to start with 1 instead of 0, and switched initial placement of “#” and " " so as to start line 1 with a ‘#’ instead of a space.

Under the code, I/ve added line-by-line comments, to help myself and others. I hope someone finds this useful…

 var size=8;
 var str="";
 for (outerLoop = 1; outerLoop <= size; outerLoop++){
     if (outerLoop % 2 == 0){str += " ";}
     for (innerLoop = 1; innerLoop <= size; innerLoop++){
         if (innerLoop % 2 != 0){str += "#";}
         else {str += " ";}
     }
 str += "\n";
 }
 console.log(str);

This is what is happening, line by line…

  1. Create a SIZE variable to determine the number of rows and line items
  2. Create an empty variable STR where line items will be concatenated
  3. Create OUTER loop and counter (to create ROWS)
  4. IF the ROW is EVEN, start with a SPACE. For the FIRST LINE, this will be FALSE, so row will begin with a ‘#’
  5. Create INNER loop and counter, to start concatenating LINE items within each row.
  6. If LINE ITEM is EVEN (which on the first instance it will be, because the first “#” was already added) add a space to the string.
  7. But (ELSE) on ODD line items, concatenate a space.
  8. CLOSING BRACKET closes the inner loop which will repeat itself concatenating a total of “less-than-SIZE” (7)
  9. Once out of the INNER LOOP and all 8 line items have concatenated, a line break gets added to the string.
  10. With the outermost closing bracket, the OUTER LOOP REPEATS 7 times ( “< size”).
  11. Once each OUTER LOOP HAS FINISHED, each line gets displayed on the JS console.
4 Likes

Triangle Loop

var str=“”;
for (r=0;r<7;r++){
   str += “#”;
  console.log(str);
}


FizzBuzz

for (n=1;n<101;n++){
  let str="";
   if (n % 3 == 0){str+="Fizz";}
   if (n % 5 == 0){str += "Buzz";}
   if (str.length == 0){str=n;}
   console.log(str);
}


ChessBoard

var size=8;
var str="";
for (n=0;n<size;n++){
   if (n % 2==0){str += " ";}
   for (r=0;r<size;r++){
     if (r % 2 ==0){str += "#";}
     else {str += " ";}
   }
str += "\n";
}
console.log(str);

1 Like

Triangle Loop

var rowHeight = 7;
var printRow = “#”;
for (let row = 0; row < rowHeight; row++) {
console.log(printRow);
printRow += “#”;
}

FizzBuzz Loop

This one took me a couple of hours to debug, lol. I had to mess around with
the order as that seemed to matter. It felt pretty good when I got it though!
Obviously you can replace console.log with document.write, to see how this
looks on the page.

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

Chessboard

let gridSize = 8;
let gridSpace = "";
for (let gridHeight = 0; gridHeight < gridSize; gridHeight++) {
  for (let gridWidth = 0; gridWidth < gridSize; gridWidth++) {
    if ((gridWidth + gridHeight) % 2 == 0) gridSpace += " ";
    else (gridSpace += "#");
  }
    gridSpace += "\n";}
console.log(gridSpace);

EX1
Triangle Loop shorten decision

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

EX2
FizzBuzz

    var Number=1;
    var lim=101;
    var devis1=3
    var devis2=5
    while (Number<lim){
              switch (true){
          case  Number%devis1==0 && Number%devis2==0:
            console.log("FizzBuzz");
                Number++;
                break;
          case  Number%devis1==0:
              console.log("Fizz");
                Number++;
                break;
          case  Number%devis2==0:
                console.log("Buzz");
                Number++;
                break;
          default:
            console.log(Number);
              Number++;
          break;
                }
          }

EX3 ChessBoard

              var size=8;
              var print="";
                      for (row_num=0; row_num<size; row_num++){
                           if ( row_num % 2 == 0 ){
                                        for (str_num=0; str_num<size; str_num++){
                                          if ( str_num % 2 == 0 ){print+="#";}
                                          else {print+=" ";}
                                                                          }
                                      }
                           else  for (str_num=0; str_num<size; str_num++){
                             if ( str_num % 2 == 0 ){print+=" ";}
                             else {print+="#";}
                             }
                             console.log(print);
                             print="";
                      }

Looping Triangle (shortest code)

for (var texto = “”; texto.length <7; console.log(texto+="#")){}

FizzBuzz (Not the shortest, ha ha ha)
I went down the If-nested path

var veces=100;

        for (var i=1; i<=veces;i++)
        {
          if (i%3===0){console.log("fizz");}
          else {
                if (i%5===0 && !i%3===0) { console.log("buzz");}
                else {console.log(i);}
               }

//2nd part

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

ChessBoard Loop

var textToDisplayOdd;
var textToDisplayEven;
var i;

  let checkBoardSize=Number(prompt("What size of checkboard?"));

//create string to show (textToDisplay)

  for (i=1; i<=checkBoardSize;i++){
    if (!(i%2===0)){textToDisplayOdd+=" ";
                    textToDisplayEven+="#";}
    else{textToDisplayOdd+="#";
         textToDisplayEven+=" ";}
  }

//Display the ChessBoard

  for (i=1;i<=checkBoardSize;i++){
      if (i%2===0) {
        console.log(textToDisplayEven);
                    }
      else {console.log(textToDisplayOdd);}
  }

Nice Looping Triangle. I didnt use the .length at first but when I saw your code I ended up with this :

for (var texto = “”; texto.length <7; console.log(texto+="#")){}

1 Like

Hi Guatemala (José),

Thanks for your comment. I tried your code but it didn’t work for me. Did it work for you? I’m not sure that you can include "console.log within the function parameters.

Let me know. It’s exciting to see how the same problem can be solved in so many different ways and the trick is to find the simplest solution that works.

Saludos!

1 Like

FizzBuzz Loop

for (a=1; a<=100; a++) {
if (a % 5==0 && a % 3 == 0) console.log(“buzzfizz”)

else if (a % 3 == 0) console.log(“fizz”)

else if (a % 5==0) console.log(“buzz”)

else console.log(a);
}

Hey, guys,
Can someone tell me why the loop function in the browser does not work? Is there something wrong with this code?

var texttodisplay = “helloooooo”;

var counter = 0;

var shouldcontinue = true;
while(shouldcontinue){
document.write(" counter is now “+counter+” “+texttodisplay+” ");
counter = counter+1;

if(User Presses Mouse Key){
shouldcontinue = false;
}

}

Kind regards
Daniel

for (var tic = “”; tic.length <7; console.log(tic+="#")){}

the colons were disturbed by the text editor.
This works :0) Just need to change the colons, Dont know why this text edit changes them (the first empty ones)

its because you have copy+pasted and that changes the colons to another type of colons.
check them and try again

I’ve corrected them- it doesn’t work either ):

Hi Danny!

I’ve posted a picture.
And now I see how nestable javaScript can be. Im really amazed. this really widens the posibilities for code making a true art.

Cheers from Guatemala!

Chess Board

I created that code, but it works in very strange way:

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

honestly everyone, i have been struggling with these exercises for the past, not joking 7 days!!! ive been stuck on this chapter trying to learn and grasp JS coding thus far and I could not do the exercises on my own, i had to google the code and after seeing what i had to code to make the last exercise specially! i was very discouraged to find how much code it would have taken me to solve that. I am feeling a bit discouraged after this, can anyone help me, point me in the right direction, i keep reading over and over and just cannot grasp it all, i feel that i would do better if i was actively practicing and coding everyday but i currently do not work in computer programming, is there any app or option out there that i can use to become more fluent with this where i am constantly practicing and coding? i learn better when it is hands on. thank you.

2 Likes

Hi ItsBad,

I’ve also been struggling with the Chess Board exercise for a few days trying to come with an optimal solution. Please don’t despair. Reading some of the answers, I found Iris’s solution very elegant and not too complicated. It’s still difficult to understand for beginners like you and me, but it’s a good exercise to study. Something that has helped me is this…

Before writing a single line of code, draw a diagram in your native language, and solve the puzzle step by step, going from the most generic aspect of the problem to the most specific.

If you cannot explain it in words, as if you were instructing a child what steps to take, trying to write the code from scratch becomes very difficult. Once you are able to articulate each step, in your own language and with diagrams, then you can start turning that into code.

I hope this helps. Best wishes!