Chapter 2 Exercises


#83

1.Looping a triangle A
var name = " # # # #\n# # # # ";
var text = “”;
for (i = 0; i < 5; i++){
text += name + “\n”;
}
console.log(text);

Looping a triangle B
var row = “”;
for (i = 1; i <= 7; i++) {
row = row + “#”;
console.log(row);
}
2. FizzBuzz A
for (i = 1; i <= 100; i++){
if (i % 3 == 0){
console.log(“Fizz”);
} else if (i % 5 == 0){
console.log(“Buzz”);
} else {
console.log(i);
}
}
FizzBuzz B
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);}
}
3. ChessBoard
var board = 8;
var string = ‘’;
for (row = 0; row <= board; row++){
for (col = 0; col <= board; col++){
if ((row + col) % 2 == 0){
string += ‘ ’;
} else {
string += ‘#’;
}
}
string += ‘\n’;
}
console.log(string);


#84

Chapter 2 Exercises

Looping a triangle

I tried this three different ways (after Ivan’s demonstration), as I thought it unnecessary to use two for loops for the task.

Triangle (by nested ‘for’ loops)

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

Triangle (by While loop)

I thought I might be able to make this simpler and wanted to try the other looping methods, so here is my (while loop) version. Also, in the book the writer gave a hint to use the length attribute of the variable!
var maxLength=7;
var toPrint="#";
while (toPrint.length<maxLength+1){
console.log(toPrint);
toPrint+="#";
}

Triangle (by Do loop)

var maxLength=7;
var toPrint="#";
do {console.log(toPrint);
toPrint+="#";
}
while (toPrint.length<maxLength+1);

Triangle (in an eloquent ‘for’ loop)

I was reasonably satisfied with the ‘Do’ loop effort, but I wondered if I could improve on the original double ‘for’ loop.
for (let toPrint="#";toPrint.length <= 7; toPrint +="#"){
console.log(toPrint);
That was pretty nice, and later I found it was virtually the same as the author’s solution, which was.
for (let line = "#"; line.length < 8; line += "#")
console.log(line);

FizzBuzz

FizzBuzz version 1

var maxnum = 100;
var num = 1;
var A = 3; // Divisible by A.
var B = 5; // Divisible by B and not by A.
printA = "Fizz";
printB = "Buzz";
do { if (num % 3 == 0) { console.log(printA);
} else if (num % 5 == 0) {console.log(printB);
} else {console.log(num);
} num++;}
while (num <= maxnum);

That worked on the first try, now to do the modified version.
var maxnum = 100;
var num = 1;
var A = 3; // Divisible by A.
var B = 5; // Divisible by B and not by A.
printA = "Fizz";
printB = "Buzz";
printC = "FizzBuzz"; // If num is divisible by both A and B.
do { if (num % 3 == 0 && num % 5 == 0) { console.log(printC);
} else if (num % 3 == 0) { console.log(printA);
} else if (num % 5 == 0) {console.log(printB);
} else {console.log(num);
} num++;}
while (num <= maxnum);

The writer’s version (below) was even shorter! I noticed that he likes to use inline ‘let’ statements rather than declaring ‘var’ before everything else.

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 (Failed attempt!)

This failed in the do … while loop!
(Printing the variables was just for testing.)

var black = "#"; console.log("black is "+ black);
var white = " "; console.log("white is " + white);
var gridWidth = 8; console.log("gridWidth is " + gridWidth);
var gridHeight = 8; console.log("gridHeight is " + gridHeight);
var newLine = "\n"; console.log("newLine is " + newLine);
var grid = white; console.log("grid is \"" + white + "\"");
var nextSpot = black; console.log("nextSpot is " + nextSpot);
var gridLength = gridWidth * gridHeight; console.log("gridLength is " + gridLength);
do { grid = grid + nextSpot;
if ((grid.length + 1) % gridWidth == 0) {nextSpot=newLine;}
else if (nextSpot==black) {nextSpot=white;}
else if (nextSpot==white) {nextSpot=black;} }
while (grid.length < (gridLength + 1));

console.log(grid);

I had been trying to make sure that at each gridWidth the next character would be the newLine, but my loop wouldn’t work! I was pretty sure that the addition of the newlines would mess up the string length max, I figured that I would adjust for that after I got a somewhat working model. :frowning: I got that slight headache that the author suggest was excuse enough to look at his answer!

Here is the author’s solution. I had to stare at it for a while to realise that the newline came in in the OUTER loop.

Part of my problem may have been that I had been trying to do everything in a single loop.

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


#85

Looping a triangle

  <script>

  // Looping a triangle - version 1, without nested loops

    var triangleLine = ""

    for (count = 0; count < 7; count++) {
      triangleLine = triangleLine + "#";
      document.write(triangleLine + "<br \>");
    }

  </script>

    <script>

  // Looping a triangle - version 2, without nested loops, with use
  // of .length

    let triangleBase = "#######";
    let triangleLine = "";
    let maxLength = triangleBase.length;

    for (count = 0; count < maxLength; count++) {
      triangleLine = triangleLine + "#";
      console.log(triangleLine);
    }

  </script>

Fizzbuzz

  <script>

  //FizzBuzz, part1, version 1 (Fizz/Buzz), using nested if/else

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

  //FizzBuzz, part2, version 1 (Fizz/Buzz/BuzzFizz), using nested if/else

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

  //FizzBuzz, part1, version 2 (Fizz/Buzz), using continue

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

  //FizzBuzz, part2, version 2 (Fizz/Buzz/BuzzFizz), using continue

  for (count=1; count<=100; count++) {
    if ((count % 3 == 0) && (count % 5 == 0)) {
      console.log("BuzzFizz");
      continue;
    }

    if (count % 3 == 0) {
      console.log("Fizz");
      continue;
    }

    if (count % 5 == 0) {
      console.log("Buzz");
      continue;
    }
    console.log(count)
  }

  </script>

Chessboard

      <script>

      // chessboard

      var size = 8;
      var chessboard = "";

      for (row = 1; row <= size; row++){
        for (column = 1; column <= size; column++){
          if ((row + column) % 2 == 1){
            chessboard = chessboard + "#";
          }
          else {
            chessboard = chessboard + " ";
          }
        }
        chessboard = chessboard + "\n";
      }
      console.log(chessboard);

      </script>

#86
// looping a triangle  
   var item = "#";
   counter = 0;

   while (counter < 7 ) {
     console.log(item);
     item += "#";
     counter++;
   } 
   

// FizzBuzz
for (var 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) || (number % 3 == 0)) {
	    console.log("Buzz")
  }

    else {
	    console.log(number)
  }
}

//chessboard
var size = 8;
var square = "";

for (var row = 0; row < size; row++) {
  for (var col = 0; col < size; col++) {
  
    if ((row + col) % 2 == 0) {
      square += " ";
    }

    else {
      square += "#";
    }
  }
  square += "\n"
}

#87

//Exercise 1:

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

//Exercise 2:
for(var count = 0; count < 101; count++)
{
if(count%3==0&&count%5==0){console.log(“FizzBuzz”);}
else if(count%3==0){console.log(“Fizz”);}
else if(count % 5==0){console.log(“Buzz”);}
else {console.log(count);}
}

//Exercise 3:
for (var row=0; row<=8; row++){
var toPrint = “”;

for (var col=0; col<=8; col++){
    if (row%2==0){
      if (col%2==0){
          toPrint+=" ";
        }
      else(toPrint+="#");
    }
      else if (col%2==0){
        toPrint+="#";
    }
    else (toPrint+=" ");
        }

  console.log (toPrint);

}

#88

im not even going to put answers. i would just copy. this was tough for a beginner


#89

Here is my Chess Board.

  <head>

  </head>

   <body>
<p>Welcome to Ivan on tech coding course</p>
<h1>This is the title</h1>

<script>
var boardLength = 8;
var i = 0;
var swap = 1;
var swap1 = " #";
var swap2 = "# ";
var row1 = swap1 + swap1 + swap1 + swap1;
var row2 = swap2 + swap2 + swap2 + swap2;
var row;
var r = 1;
var i = 1;
function PlayChess() {
  while (i <= boardLength) {
    if (swap == 1) {
    console.log(row1);
    swap = 2;
    }
    else if (swap == 2) {
      console.log(row2);
      swap = 1;
    }
    else {
      console.log("ERROR");
    }
    i = i + 1;
  }




}

PlayChess()
</script>

   </body>

</html>

Here is my FizzBuzz

  <head>

  </head>

   <body>
<p>Welcome to Ivan on tech coding course</p>
<h1>This is the title</h1>

<script>

var log = false;
//Toggles non error logs on and off. Check function LogFile() for more info.

function LogFile() {
  if (log == true) {
    console.log("Log: f = " + f + " and b  = " + b);
//Runs logs
  }

}
var f = 0;
// a is i divided by 3 and is equivlannt to f

var b = 0;
// b is i divided by 5
var i = 0;
// i is the number of times the loop is on
while (i < 101) {
//MATTTTHHHHHH
  f = i % 3;
  b = i % 5;
  i = i + 1
  if(f == 0 && b == 0) {
    console.log("FuzzBuzz");
    LogFile()
    //If divides invenly into 3 & 5
  }
  else if (f == 0) {
    console.log('fuzz');
    LogFile()
    // if doesn't divide evenly into a
  }

  else if (b == 0 && f > 0) {
    console.log('Buzz');
    LogFile()
  }

  else if (f > 0 && b > 0) {
    console.log(i);
    LogFile()
    //Buzz
  }
  //**/
  else {
    console.log("Error Log: Fuzz = " + f + " and Buzz  = " + b);
    // If everything works this should never appear
  }
  //*/
}

</script>

   </body>

</html>

Edit: Seems to reformat code…Think I fixed it?


#90

Hi everybody!!
I’ve started writting the “FIZZBUZZ” excercise and I can not undersand the mistake I made.
If someone could helpme I would realy appreciated. Thanks!

Here goes the program I wrote:

  for(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)&&(1%5==0)){
      console.log('FizzBuzz');
    }else{
      console.log(i);
    }
  }

#91

Nevermind it was a silly error.

I forgot putting a pair of roundbrackets :sweat_smile:

Here goes the correction:

  for(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{
      console.log('FizzBuzz');
    }
  }

#92

Here goes my CHESSBOARD excercise (although, I think it’s not what’s expected) :thinking:

  let patternA=' # # # #'
  let patternB='# # # # '
  for(x=1; x<=8; x++){
    if((x%2===0)){
      console.log(patternA);
    }else{
      console.log(patternB);
    }
  }

#93

Hey body,
I traid running your program of “CHESSBOARD” on my console but it founds en error when doing so.


#94

FizzBuzz

  for(var count =1; count < 101; count++)
    {
      if((count%5==0)&&(count%3==0))
      {console.log("FizzBuzz");}

      else if((count%5==0) && (count%3!=0))
      {console.log("Buzz");}

      else if (count%3==0)
      {console.log("Fizz");}

      else console.log(count);
  }

ChessBoard

  var row=8;
  var column=4;
  var boardCharacter="#";
  var finalBoard="";

  for (var count=0;count<row;count++)
  {
    if(count%2==0)
    {
      for(count2=0;count2<column;count2++)
      {
        finalBoard+=" " + boardCharacter;
      }
    }
    else for(count2=0;count2<column;count2++)
    {
      finalBoard+=boardCharacter + " ";
    }
    finalBoard=finalBoard+"\n";

  }
  console.log(finalBoard);

#95

Try breaking the problem down into simple tasks, and post your program for that part only. You can build on that with the help of others.

For Fizzbuzz, maybe start with printing numbers from 1 to 100.


#96

//triangle
for(var a=0; a<7; a++){
var x="#";
for(var b=0; b<a; b++)
x+="#";
console.log(x);
}

//FizzBazz
for(var d=0; d<101; d++){

if((d%3==0) && (d%5==0)){
console.log(“FizzBazz”);
}
else if(d%3==0){
console.log(“Fizz”);
}
else if(d%5==0){
console.log(“Bazz”);
}
else {
console.log(d);
}
}

//chessboard
var size = 8;
var chessboard="";
for (var check = 0; check < size; check++) {
for (var mate = 0; mate < size; mate++) {
if ((check + mate) % 2 == 0){
chessboard+=" “;
}
else{
chessboard+=”#";
}
}
chessboard+="\n";
}
console.log(chessboard);


#97
// Looping A Triangle Exercise

for(var row=1; row<8; row++){
  console.log("#".repeat(row))
}

// FizzBuzz Exercise
for(var i=1; i<101; 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);
  }
}

// Chessboard 
var size = 8
var board = ""
for(var r = 0; r < size; r++ ){
  for(var c = 0; c < size; c++){
    if((r+c) %2 == 0){
      board += " "
    }else{
      board += "X"
    }
  }
 board += "\n"
}

thanks to @Guactoshi for the cool Chessboard solution. :hear_no_evil: I’m still struggling to understand it fully. So ill tried it on paper, line by line.


#98
  1. Loopingatriangle
  textToPrint = "#"
  for(var i=0; i<7; i++){
    console.log(textToPrint);
    textToPrint += "#";
  }
  1. Fizz Buzz
    First Task:
for(var i=1; i<=100; i++){
   if(i % 3 == 0){console.log("Fizz");}
   else if(i % 5 == 0){console.log("Buzz");}
   else {console.log(i);}
}
Second Task:
 for(var 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);}
   }
  1. Chessboard
  var size = 8;
  var textToDisplay = "";
  for(var i=0; i<size; i++){
    for(var j=0; j<(size/2); j++){
      if(i % 2 == 0) {textToDisplay += " #";}
      else{ textToDisplay += "# ";}
    }
   if(size % 2 != 0){textToDisplay = textToDisplay.slice(0, -1);}
   console.log(textToDisplay);
   textToDisplay = "";
  }

#99

@FizzBuzz solution:
if you just change the order of the two “else if statements” you do not need to check if count%5 == 5 and count%3 != 0.


else if (count%3==0) {console.log(“Fizz”);}
else if((count%5==0) {console.log(“Buzz”);}

the second line can only be reached if count%3 is not equal to zero


#100

i did start with 1 to 100 and did it. then i couldnt go from there. and when i looked at the answer it wasnt even close.


#101

Triangle

        var p = "#";
       for(var r = 0; r < 7; r++){
           for(var c = 0; c <= r; c++){
             console.log(p);

           };
             p = p + '#';
       };

FizzBuzz

        var x3 = 0;
        var x5 = 0;

       for(var i = 0; i < 100; i++){
         if (x3 == 3 && x5 == 5){
           console.log("FizzBuzz");
           x3 = 0;
           x5 = 0;
         }
         else if (x3 == 3 && x5 != 5){
           console.log("Fizz");
           x3 = 0;
         }else if (x3 != 3 && x5 == 5){
           console.log("Buzz");
           x5 = 0;
         }else{
           console.log(i);
         };
      };

Chessboard

     var size = 10;
     var board = '';
       for (var rows = 0; rows < size; rows++){
            for (var column = 0; column < size; column++){
                  if ((rows + column)%2 == 0){board += " ";
                  }else{board += "#";}
            }
        board += '\n';
       }
       console.log(board);

#102

EX 1

var row_max = 7;
for (var row_count = 0; row_count < row_max; row_count++)
{
var toPrint = “#”;

  for (var col_count = 0; col_count < row_count; col_count ++)
  {
  	toPrint += '#';	
  }		
  console.log(toPrint);

}
//END EX 1

EX 2

var num_max = 100;
var num_print = 1;

for (var num_count = 0; num_count < num_max; num_count++)
{

  if (num_print % 3 == 0 && num_print % 5 != 0)
  {
  	console.log("Fizz");	
  }
  else
  if (num_print % 5 == 0 && num_print % 3 != 0)
  {
  	console.log("Buzz");		
  }
  else
  if (num_print % 3 == 0 && num_print % 5 == 0)
  {
  	console.log("FizzBuzz");		
  }
  else
  {
  	console.log(num_print);	
  }
  num_print++;

}
//END EX 2

EX 3

var gridChar = “#”;
var gridSpace = " ";

var gridSize = 8;

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

  if (i % 2 == 0)
  {
  	var gridLine = gridSpace + gridChar;
  	for (var j = 1; j < gridSize; j++)
  	{
  		gridLine += gridSpace + gridChar;
  	}
  	console.log(gridLine);				
  }
  else
  {
  	var gridLine = gridChar + gridSpace;
  	for (var k = 1; k < gridSize; k++)
  	{
  		gridLine += gridChar + gridSpace;
  	}
  	console.log(gridLine);
  }

}
//END EX 3