Chapter 2 Exercises

//Looping a Triangle Exercise
var poundSign = “#”;
for (counter = 1; counter < 8; counter = counter + 1)
{
for (counter2 = 0; counter2 < counter; counter2 = counter2 + 1)
{console.log(poundSign);
}
console.log("
");
}

/*
FizzBuzz
Write a program that uses console.log to print all
the numbers from 1 to 100, with two exceptions. For numbers
divisible by 3, print “Fizz” instead of the number, and for numbers
divisible by 5 (and not 3), print “Buzz” instead.
When you have that working, modify your program to print
“FizzBuzz” for numbers that are divisible by both 3 and 5
(and still print “Fizz” or “Buzz” for numbers
divisible by only one of those).
*/

//Part 1 (For numbers divisible by 3 print “Fizz”, and for divisible by 5, print “Buzz”
var numberLimit = 101;

// Add For Loop for running through numbers 1 thru 100
//for each number, check is the number is dvisible by 3
//if divisible by 3 print “Fizz”
//else if divisible by 5 print “Buzz”
//else print the number.

for (counter = 1; counter < numberLimit; counter++)
{
if (counter % 3 == 0)
{
console.log(“Fizz”);
}
else if (counter % 5 == 0)
{
console.log(“Buzz”);
}
else {
console.log(counter);
}

}

// ***********************************************//
//Part 2 of Fizz Buzz **
var numberLimit = 101;

// Add For Loop for running through numbers 1 thru 100
//for each number, check is the number is dvisible by 3
//if divisible by 3 print “Fizz”
//else if divisible by 5 print “Buzz”
//else print the number.

for (counter = 1; counter < numberLimit; counter++)
{
if ((counter % 3 == 0) && (counter % 5 == 0))
{
console.log(“FizzBuzz”);
}
else if (counter % 3 == 0)
{
console.log(“Fizz”);
}
else if (counter % 5 == 0)
{
console.log(“Buzz”);
}
else {
console.log(counter);
}

}

/*
Chessboard
Write a program that creates a string that represents an 8×8 grid,
using newline characters to separate lines. At each position of the
grid there is either a space or a “#” character. The characters should
form a chessboard.
Passing this string to console.log should show something like this:

When you have a program that generates this pattern, define a binding size
= 8 and change the program so that it works for any size, outputting a grid
of the given width and height.

*/

//Gridsize is the size of the checkboard grid
//Print mode controls whether a “#” is printed or a blank { mode = 0 is blank, mode = 1 is a ‘#’}
//Create For Loop for overall Grid
//Create a For Loop within the For loop above to alternate prints of # and bank spaces
var width = 8
var height = 8
var mode = 0
var grid = “”; //holder for the Grid

for (counter = 1; counter < height + 1; counter ++)
{

for (counter2 = 1; counter2 < width + 1; counter2++)
{
if (mode == 0)
{
grid = grid + " ";
mode = 1;
}
else if (mode == 1)
{
grid = grid + “#”;
mode = 0;
}
}
if (mode == 0)
{mode = 1; }
else
{mode = 0; }
grid = grid + ‘\n’;

}

console.log(grid);

1 Like

FizzBuzz

var totalNumbers = 100;

for (var number = 1; number <= totalNumbers; 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);
}
1 Like

Chessboard:

var gridSize = 8;
var outputEvenRows = " #";
var outputOddRows = "# ";

// Create even numbered Row
for (var currentColumn = 1; currentColumn < gridSize; currentColumn++){
  outputEvenRows = outputEvenRows + " #";
}
// Create odd numbered Row
for (var currentColumn = 1; currentColumn < gridSize; currentColumn++){
  outputOddRows = outputOddRows + "# ";
}

// Print the correct number of rows
for (var currentRow = 1; currentRow <= gridSize; currentRow++){
  if (currentRow % 2 == 0) console.log(outputEvenRows);
  else console.log(outputOddRows);
}
1 Like

That was fun. FYI I’ve actually had the “FizzBuzz” question in an interview, so this is completely legit! I’m also including my solution to the triangle exercise as I found a better solution.

E1: Looping Triangle

Since each new row only adds another char you can save the previous row and just append another char. In computer science terms this makes it O(n) instead of O(n^2).

<html>
    <head>
        <title>EJ Ch2 Ex1</title>
    </head>
    <body>
        <h1>EJ Ch2 Ex1 - Looping Triangle</h1>        
        <script>
            const rows = 7;
            const charToPrint = "#";
            for(let i=0, toPrint=charToPrint; i<rows; i++, toPrint+=charToPrint) {
                console.log(toPrint);
            }
        </script>
    </body>
</html>
E2 - FizzBuzz
<html>
    <head>
        <title>EJ Ch2 Ex2</title>
    </head>
    <body>
        <h1>EJ Ch2 Ex2 - FizzBuzz!</h1>        
        <script>
            const n = 100;
            for(let i=1; i<=n; i++) {
                let toPrint = "";
                const divBy3 = i % 3 == 0;
                const divBy5 = i % 5 == 0;
                if (divBy3) {
                    toPrint += "Fizz";
                }
                if (divBy5) {
                    toPrint += "Buzz";
                }
                if (!divBy3 && !divBy5) {
                    toPrint = i;
                }
                console.log(`${toPrint} (i:${i}, divBy3:${divBy3}, divBy5:${divBy5})`);
            }
        </script>
    </body>
</html>
E3 - Chessboard

This one is a bit more complicated as it’s a general solution that only does the work of generating the odd and even rows once. This is an optimization as any row after the first 2 would be repeating work that’s already been done as they’re identical. Again this makes it O(n) instead of O(n^2).

<html>
    <head>
        <title>EJ Ch2 Ex3</title>
    </head>
    <body>
        <h1>EJ Ch2 Ex3 - Chessboard</h1>        
        <script>
            const gridSize = 8;
            const blackChar = "#";
            const whiteChar = " ";
            let evenRowText = "";
            let oddRowText = "";
            for(let i=0; i < gridSize; i++) {
                const isEvenRow = i % 2 == 0;
                let toPrint = "";
                if (isEvenRow) {
                    if (!evenRowText) {
                        // construct even row text
                        for(let j=0; j<gridSize; j++) {
                            // print white char if even, black char if odd
                            if (j % 2 == 0) {
                                evenRowText += whiteChar;
                            } else {
                                evenRowText += blackChar;
                            }
                        }
                    }
                    toPrint = evenRowText;
                } else {
                    if (!oddRowText) {
                        // construct odd row text
                        for(let j=0; j<gridSize; j++) {
                            // print black char if even, white char if odd
                            if (j % 2 == 0) {
                                oddRowText += blackChar;
                            } else {
                                oddRowText += whiteChar;
                            }
                        }
                    }
                    toPrint = oddRowText;
                }
                console.log(toPrint);
            }
        </script>
    </body>
</html>
1 Like

//EXERCISE loopingTriangle
var num_row =7;
for (var row =0; row < num_row; row++){
var toPrint = “#”;

  for(var column = 0; column<row; column++){
    toPrint += "#";
  }
  console.log(toPrint);
}

//EXERCISE FizzBuzz
for (var fb = 0; fb <= 100; fb++){
var print = “”;
if (fb % 3 == 0) print += “Fizz”;
if (fb % 5 == 0) print += “Buzz”;
console.log(print || fb);}

//EXERCISE CHESSBOARD
var row = 8;
var column = “”;

for (var v = 0; v <= row; v++) {
for (var h = 0; h <= row; h++) {
if ((h + v) % 2 == 0) {column += " ";}
else {column += “#”;}
}
column += “\n”;}
console.log (column);

1 Like
  1. Looping a Triangle:
    for (let a = ‘#’; a.length < 8; a += ‘#’) {
    console.log(a)
    }

  2. FizzBuzz:
    for (let a = 1; a <= 100; a++) {
    if (a % 3 == 0) { console.log(‘Fizz’) }
    if (a % 5 == 0) { console.log(‘Buzz’) }
    if ((a % 3 == 0) && (a % 5 == 0)) { console.log(‘FizzBuzz’)}
    console.log(a);
    }

  3. Chessboard
    For this exercise I couldn’t found the solution on my own, I did try to solve it for few hours :frowning: so I will just copy paste the solution from the book.

let size = prompt("Enter the size of the board: ");
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

After several hours of toying around, here are my solutions. I went for document.write solutions, as I like to be able to see how things look on a web page. I’m looking forward to learning how to write more elegant/less chunky code!

Triangle

<script>

var h = "#"
var size = prompt("How large would you like your hash triangle to be?");

for(let number = 0; number <= size; number ++){
  document.write("<br>" + (h.repeat(number)) + "</br>");
}

    </script>

FizzBuzz

script>

var f = "Fizz";
var b = "Buzz";
var setSize = prompt("How much FizzBuzz would you like?");

for(let number = 1; number <= setSize; number ++){
  if ((number % 5 == 0)&&(number % 3 == 0)){document.write ("<br>" + f + b + "</br>");}
  else if (number % 3 == 0){document.write("<br>" + f + "</br>");}
  else if (number % 5 == 0){document.write ("<br>" + b + "</br>");}
  else {document.write ("<br>" + number + "</br>");}

}

    </script>

Chessboard

<script>

var c = "#";
var s = "\xa0";
var show = "";
var gridHeight = prompt("How tall do you want the grid to be?");
var gridWidth = (.5 * prompt("How wide do you want the grid to be?"));

  for (let a = 0; a < gridHeight; a ++){
    if (a % 2 == 0){show = (((s + c).repeat(gridWidth)) + "<br>");
  } else {show = (((c + s).repeat(gridWidth)) + "<br>");
  }
    document.write(show);
  }

        </script>
1 Like

Took some time especially to find out the corresponding expressions for the logic but I finally cracked it.

A Tringle

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(var n = 0; n < 100; n++){
var output = “”;
if(n % 3 == 0)output += “Fizz”
if(n % 5 == 0)output += “Buzz”
console.log(output||n);
}

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

1 Like

Youtube is awesome!!

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

//USE MODULUS|
for(var i=0; i<=100; i++){
if(i % 3 == 0 && i % 5 != 0){
console.log(“fizz”);
} else if (i % 5 == 0 && i % 3 != 0){
console.log(“buzz”);
} else if (i %3 == 0 && i % 5 == 0){
console.log (“fizzbuzz”);
} else{
console.log(i);
}
}

let chessboard = “####”
let chessboardA = " ####"
let counter =0

while (counter<8){
console.log(chessboard);
console.log(chessboarda);
counter++;
}

1 Like

Triangle Loop

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 (i = 0; i = 100; i++){
var output = “”;

if (i % 3 == 0){output += “fizz”;}
if (i % 5 == 0){output += “Buzz”;}
if (output == “”){output = i;}

console.log (output);

}

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

1. Looping a Triangle

    var i,j;
      for (i = 1; i <= 7; i++)
      {
        for(j = 1; j <= i; j++)
        {
          document.write("#");
        }
        document.write("<br>");
      }

2. FizzBuzz

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

3. FizzBuzz

    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 += "&nbsp;";
          else
          board += "#";
        }
        board += "<br>";
      }
      document.write(board);
1 Like

///
//code exercise triangle
var r="";
for (var i=0; i<8; i++){
for (var k=0; k<i; k++){
r+="#";
}
r+="\n";
}
console.log®;
/////
//code execise fizzbuzz
for (var i=1; i<=100; i++){
if (i%3==0 && i%5!==0){
console.log(“Fizz”);}
else if (i%5==0 && i%3!==0){console.log(“Buzz”);}
else if (i%3==0 && i%5==0){console.log(“fizzbuzz”);}
else {console.log(i);}
}
//////////
//code exercise chessboard
var i=8;
var k=" “;
for(var j=1; j<=i; j++){
for(var l=0; l<=i; l++) {
if((j+l)%2==0){
k+=” “;} else {
k+=”#";
}
}
k+="\n";
}
console.log(k);

1 Like

Triangle

var output = “”;

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

FizzBuzz

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

function checkMultiple(number, factor) {
    if (number % factor == 0)
      return true;
    else
      return false;
}

var currentNumber = i + 1;
  
if (checkMultiple(currentNumber, 15))
    console.log("FizzBuzz");
else if (checkMultiple(currentNumber, 3))
    console.log("Fizz");
else if (checkMultiple(currentNumber, 5))
    console.log("Buzz");
else
    console.log(currentNumber)

}

Chessboard

function generateBoard(size){

var evenRow = “”;
for(i = 0; i < size; i++)
evenRow += "# ";

var oddRow = “”;
for(i = 0; i < size; i++)
oddRow += " #";

for(i = 0; i < size; i++){
if(i % 2 == 0)
console.log(evenRow);
else
console.log(oddRow);
}
}
generateBoard(8);

1 Like

FizzBuzz

script type=“text/javascript”

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

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

ChessBoard

script type=“text/javascript”

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 += "&nbsp;";
  else
    board += "#";
  }
  board += "<br>";
}

document.write(board);

1 Like
 // Looping a triangle
      let x = "#";
      for(let i=0;i<7;i++) {
        console.log(x + "\n");
        x+="#";
      }
     // FizzBuzz 3-Fizz 5-Buzz
      for(let i=1;i<=100;i++) {
        if (!(i % 15)) console.log("FizzBuzz \n");
        else if (!(i % 3)) console.log("Fizz \n");
        else if (!(i % 5)) console.log("Buzz \n");
        else console.log(i + " \n");
      }
      // Chessboard
      let chessboard = "", w=8, h=8;
      for(let i=0;i<h;i++) {
        for(let j=0;j<w;j++) {
          if (!((i+j) % 2)) {
            chessboard+= " ";
          }
          else {
            chessboard+= "#";
          }
        }
        chessboard+= " \n";
      }
      console.log(chessboard);
1 Like
//Looping a triangle
let str = '#';
const numRows = 7;

for (let i=0; i<numRows; i++){
  console.log(str);
  str += '#';
}

//FizzBuzz
let i = 0;
while(i<100){
  if((i%3===0) && (i%5!==0)){
    console.log(i + ': Fizz');
  }
  if((i%5===0) && (i%3!==0)){
    console.log(i + ': Buzz');
  }
  if((i%3===0) && (i%5===0)){
    console.log(i + ': FizzBuzz');
  }
  i++;
}

//Chessboard
const size = 8;
let printHash = '';
for(let j=0; j < size; j++){
  if(j%2===0){
    for(let i=0; i < size*2; i++){
      if(i%2===0 ? printHash += ' ' : printHash += '#');
      }
  } else {
    for(let i=0; i < size*2; i++){
      if(i%2===0 ? printHash += '#' : printHash += ' ');
    }
  }
  console.log(printHash);
  printHash = '';
}
1 Like

var numto100=100;

for (var num=0; num<numto100; num++){

if(num%3==0){
    document.write("<h1>Num is divisible by 3"+" "+num+"</h1>");
} else if (num%5==0) {
    document.write("<h1>Num is divisible by 5"+" "+num+"</h1>");
}

}

This is my previous code, I did before without any help.

for (var num=0; num<numto100; num++){

if(num%3){

    document.write("<h1>Num is divisible by 3"+" "+num+"</h1>");

} else if (num%5) {

    document.write("<h1>Num is divisible by 5"+" "+num+"</h1>");

}

}

Why does we need the == operator? my code didn’t work until I added the == 0.

Not understanding the logic behind it.

//Ex.1

LOOPING A TRIANGLE


ToShow="";
for(counter=0; counter<7;counter++){
ToShow+="#";
document.write(ToShow+"
");
}
//Ex.2

FIZZBUZZ


for(counter=1; counter<=100; counter++){
W3=""; W5=""; ToShow=counter;
if(counter%3==0){W3=“Fizz”; ToShow=W3+W5;};
if(counter%5==0){W5=“Buzz”; ToShow=W3+W5;};
document.write(ToShow+"
");
}
//Ex.3

CHESSBOARD


r_size=8; c_size=8;
for(r=1;r<=r_size;r++){
for(c=1;c<=c_size;c++){
if((r+c)%2==0){document.write("&nbsp");}
else document.write("#");
}
document.write("
");
}
1 Like

problem 1
a.
let size = 100
for(num= 0; num < size; num++){
if(num % 3 == 0){
console.log(“fizz”);
} else if( num % 5 == 0){
console.log(“buzz”);
} else console.log(num);
}

b.
for(num= 0; num < size; num++){
if (num % 3 == 0 && num % 5 == 0){
console.log(“Fizzbuzz”);
}
else if (num % 3 == 0){
console.log(“fizz”);
} else if( num % 5 == 0){
console.log(“buzz”);
} else console.log(num);
}

Problem 2
a.
let size = 8
let chessboard = “”
for(row = 0; row < size; row++){
for (column = 0; column < size; column++){
if((column + row) % 2 === 0)
chessboard += “#”;
else
chessboard += " ";
}
chessboard += “\n”;
}

b.
let size1 = user prompt(“length”)
let size2 = user prompt(“width”)
for(row = 0; row < size1; row++){
for (column = 0; column < size2; column++){
if((column + row) % 2 === 0)
chessboard += “#”;
else
chessboard += " ";
}
chessboard += “\n”;
}

1 Like

Hello sir, for which exercise you use that code? will be happy to help you but i need more details.

If you have any doubt, please let us know so we can help you! :slight_smile:

Carlos Z.