Chapter 2 Exercises

FIZZBUZZ

for(var number = 0; number <100; number ++)
if (number%5 === 0 && number%3 === 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

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

1 Like

Sweet baby Jesus! this took me a long while to figure this one out.
Banged me head on the wall a couple of times had to have a nap but manage to do it at the end :sunglasses:

Chessboard

x = 8;
chessboard = “”;
for (var rows = 0; rows < x; rows++) {
for (var columns = 0; columns < x; columns++) {
if((rows+columns)%2 == 0){
chessboard += " ";
} else {
chessboard += “#”;
}
}
chessboard+= “\n”;
}
console.log(chessboard);

1 Like
// HTML output version of Looping a Triangle - I had my own implementation
let triangle = "";
for (let i = 0; i < 7; i++) {
    triangle += "#";
    document.write(triangle,"<br />");
}

// FizzBuzz
for (let i = 1; i < 100; i++) {
    if(i % 3 === 0 || i % 5 === 0) {
        if(i % 3 === 0 && i % 5 === 0)
            console.log('FizzBuzz');
        if (i % 3 === 0) {
            console.log('Fizz');
        } if (i % 5 === 0){
            console.log('Buzz');
        }
        continue;
    }
    console.log(i);
}


// Chessboard - This was a pain!!!!
let dimension = 8;
let hash = "";

for (let i = 0; i < dimension; i++) {
    for (let j = 0; j < dimension; j++) {
        if((j + i) % 2 === 0) {
            hash += ' ';
            continue;
        }
        hash += '#';  
    }
    hash += '\n';
}

console.log(hash);
1 Like

Fizz Buzz

for (counter = 0; counter <= 100; counter++){
if (counter %15 == 0) console.log(“FizzBuzz”);
else if (counter %3 == 0) console.log(“Fizz”);
else if (counter %5 == 0) console.log(“Buzz”);

else console.log(counter);

}

1 Like

Chess Board
It took a while to understand the loop within a loop idea. The first example looping a triangle helped with the concept. I needed help on this one and changed small parts to help me get it (number and letter grid). I think the top row is still indented one extra space on this one …

var boardSize = 8;
var squares = " ";
for(var num =0; num < boardSize; num++){
	for(var letter =0; letter < boardSize; letter++){
		if ((num + letter) % 2 == 0){
			squares += " ";

		} else {
			squares += "#";
		}
	}
			squares += "\n";
}
			console.log(squares)
1 Like

Looping a Triangle:

let ntx = “#”;

// while tx’s length is less than or equal to 7
while (ntx.length <= 7) {
// log tx to the console
console.log(ntx);
// reset ntx to be ntx plus another #
ntx = ntx + “#”;
}

Fizz Buzz:

// Create for loop code for variable to log 1 to 100 to the console
//For loop variables are declared inside of the same line as the for loop operator
//increment for loop variable by 1
for (let c = 1; c <= 100; c++) {
// Create an output variable leave value open for code
let output = “”;
// if output is divisible evenly by 3 then log Fizz to the console
if (c % 3 === 0) output += “Fizz”;
// if output is divisible evenly by 5 then log Fizz to the console
if (c % 5 === 0) output += “Buzz”;
// if output is divisible evenly by 3 and 5 then log FizzBuzz to the console
console.log(output || c);
}

Chessboard:

// create a size variable and set it equal to 8
let size = 10;
// create an empty string result
let result = ‘’;

// loop to create the rows
let row = 1;
while (row <= size){
// loop to create the columns
let column = 1;
while (column <= size){
// if column plus size is even
if ((column + row) % 2 === 0) {
// add an empty space
result += " ";
// else
} else {
// add a hashtag #
result += “#”;
}
column += 1;
}
// add a newline symbol to end current
result += ‘\n’;
row += 1;
}
// log result to the console
console.log(result);

1 Like

Triangle Loop (this did not work for me)
let a = ‘#’;
while (a.length < 8){
console.log(a); a+=a;
}

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

Chess Board
I could not solve this one on my own. I had to look at the solution. I started out like this:
let size = 8;
let hash = ‘#’;
let col = 0;
let row = 0;
When I looked at the solution, I could see I was thinking about this sort of correctly, so I feel good about that. But I now understand I could have created the column and row grid using ‘if’ statements.

Quick update on chess board; I’ve been learning about nested loops and how they work. In this case, the column and row variables start out at zero and work their way up the “less than size” variable. I added some additional text output per loop so I can try to understand how and when each variable increments. If size = 4, the inner and outer loops execute a total of 12 times to generate the chessboard:
let size =4;
let board = “”;
for(let y=0; y<size; y++){
for(let x=0; x<size; x++){
if((x+y) % 2 == 0){
board += “_”;
console.log(“y = " + y + " " + “x = " + x);
}else{
board +=”#”;
console.log("x = " + x + " " + "y = " + y);
}
}
board += “\n”;
}
console.log(board);
image

What I still don’t understand is how the col/row variables go back to zero after the increment. But I think the whole process starts over for each col/row variable until BOTH reach “less than size” at the same time.

Well this was fun! Programming for the first time ever …

The first one took me 45 minutes, but I guess on an interview I would get eliminated very fast because my code is not as short as the solution in the book :frowning:

The chess part was a bit harder… Took me about 2 days to figure out how to loop horizontaly and then have it all verticaly with breaking the line… But the last thing that I truly was strugling with was how to get each line to start with the opposite sign (because for hours I had each line looking the same, starting with empty space and then having the hashtag, and then repeating it like that)… Happy to have finally solve this and move on :slight_smile:

FizzBuzz Snimka zaslona (4)

3 Likes

TRIANGLE LOOP

  var x='';
 for(let i=0; i <8; i++){
 x= '#'+ x;
 console.log( x );
 }

FIZZ BUZZ

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

CHESSBOARD

 var totalSize = (gridSize * gridSize) + gridSize;
 var grid = "";
 for (i = 0; i < totalSize; i++) {
   if (i % (gridSize + 1) == 0)
     grid += "\n";
   else if (i % 2 == 0)
     grid += "#";
   else
     grid += " ";
}
 console.log(grid);
3 Likes

@filmnation thanks so much. trying this out on my practice website . Cant get the src code for script.
-where can i get the src code from . How did you integrate script into html.

You can see the exercise solutions here: https://eloquentjavascript.net/code/#2
You don’t have to get the source code into HTML; you can just access your browsers console and enter the code there directly. Accessing the “console” is browser specific, but in my case, I use Brave, so I hit CTRL + SHITF + i. Or, you can access the browser control menu and look for anything resembling “Tools --> developer tools”. Once you access that, you can enter code there. Remember you may have to hold the SHIFT button if you press the ENTER key to start writing code on a new line. (Otherwise, your code might execute prematurely…)

1 Like

Wow Keep up the perseverance! This is the true path towards a successful developer and you’re on it!

Happy learning! :smiley:

1 Like

Thank you so much, words of support really mean a lot. I don’t know any programmers and everyone around me thinks this is something so hard that there’s no point of even trying unless you’re 20 (and not like me, about to turn 40) :rofl: However, this has always been something interesting for me and I am happy to finally have time to learn more.

1 Like

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 += "#";
    }
    console.log(toPrint);
  }

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

FizzBuzz wasn’t bad at all for me. I got stuck on the Chessboard problem as I did a double loop with a boolean detecting if the next line would start with a blank space or a #. I got tripped up because with an even number my boolean toggle was starting every line with a blank space so they weren’t alternating. I needed to put a toggle outside of the inner loop to fix this. I also had to put a condition around the toggle in case the binding number was odd or even. Cheers.

1 Like

Looping a Triangle
let n=0;hashNum=0;

      for(n=0;n<8;n++){hashes=""
        for(hashNum=0;hashNum<n;hashNum++){
          hashes+="#"
        }
      document.write(hashes+"<br>");
    }

FizzBuzz

for(let n=0; n <= 100; n++)
{
let numPrint = n;

if (n%3==0 && n%5==0) numPrint="FizzBuzz"; 
  else if (n%3==0) numPrint="Fizz"; 
  else if (n%5==0) numPrint="Buzz"; 

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

}

ChessBoard
let row=0; let col=0;

      for (row=0;row<8;row++){
        for (col=0;col<8;col++){
          if ((row+col)%2==0) document.write("_")
          else {document.write("#")}
        }
        {document.write("<br>")}
      }
1 Like

Hello everyone! I was trying to do the fizz buzz exercise but I can’t seem to figure out what I am doing wrong. The output of this code ended up being 1 - 100 but nothing more.

image

image

I figured it out! But does anyone have advice on how to make it more succinct?

image

1 Like

I actually wrote the code first like you did and had the same intention to make it more succinct.

To do that have the conditions modify a single variable that it will print/output.

So think of it as:

document.write(VARIABLE)

Then have your “if” “else” conditions modify that “VARIABLE”

1 Like
  /* BUILD YOUR OWN CHESSBOARD */
  let enterRow = Number(prompt("How many rows?"));
  let enterColumn = Number(prompt("How many columns?"));
  let row=0; let col=0;
      for (row=0;row<enterRow;row++){
      {document.write("<br>|")};
      for (col=0;col<enterColumn;col++){
        if ((row+col)%2==0) document.write("<u>&nbsp&nbsp|</u>")
        else {document.write("<u><b>#|<b></u>")}
      }          
    }

So I had a little fun making the Chess Board assignment more flexible so that you can customize the size of the chess board you can make. its not a perfect chessboard of course. This is why I love coding, to play around like this.

Go ahead and try it out, you can make it better by adding your own adjustments to make the Chess Board look and function better.

1 Like