Chapter 2 Exercises

lol my code seems too long compared to other users…

Triangle:

      let char = '';
      let max_rows = 7;
      string=""
      for(var row = 0; row < max_rows; row++){
        string+="#"
        console.log(string)
      }

FizzBuzz:

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

ChessBoard:

      let boardsize = 11
      let lineA = ''
      let lineB = ''
      for(var counter = 1; counter <= boardsize; counter++ ){
        if (counter % 2 === 0) {
          lineA = lineA +"#";
        }
        else {
          lineA = lineA + " ";
        }
      }
      for(var counter = 1; counter <= boardsize; counter++ ){
        if (counter % 2 === 0) {
          lineB = lineB +" ";
        }
        else {
          lineB = lineB + "#";
        }
      }
      for(var row = 1 ; row <= boardsize; row++){
        if (row % 2 === 0) {
          console.log(lineA);
        }
        else {
          console.log(lineB);
        }
      }
1 Like

Fizz Buzz


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

 var filasColumnas = 4;
  strChess1 = "&nbsp;#";
  strChess2 = "#&nbsp;";
  strChess3 = "";
  strChess4 = "";
  for (var l = 0; l < filasColumnas; l++) {
    strChess3 = strChess3 + strChess1;
    strChess4 = strChess4 + strChess2;
  }

  for (var m = 1; m <= filasColumnas; m++) {
    if (m % 2 == 0) {
      document.write("<h5>"+ strChess3 +"</h5>");
    }else {
      document.write("<h5>"+ strChess4 +"</h5>");
    }
  }

EDIT by @gabba
@EdTunn use the preformatted Text tag for your code, the code displayed right now doesn’t work.
But the one with the preformatted tag is :wink:

1 Like

this assignment has totally stumped me. I have been stuck on it for a month and with only 1-2.5 hours a day to work on it I have managed to work through the model answers and dig through paste bin, you tube, read and re-read the JS chapters etc to the arrive at a point where I can mostly understand the code for each solution although, if I am honest about it, I am not yet able to truly come up with this code without some help. I did manage to complete the Defi 101 in this same time as well as get halfway through the Algo-trading. :slightly_smiling_face:
1, looping triangle.
for (let line = “#”; line.length < 8; line += “#”)
console.log(line);
2, Fizz Buzz.
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);
}
3, 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

I spent more than 6 hours trying to create a solution, consulted some tutorials and tried to do it in a different way. I managed to solve the puzzle, but I didn’t understand how hahahaha.

 <script>

       var x = 8

       var board = ""

       var count = 1

       while (count<=8) {

         for (var contagem = 1; contagem <= x ; contagem++) {

          if (( contagem + count )/2 % 2 == 0)

           board += " "  ;

          else

            board += "#";

          }

       board +="\n"; count++;
     }

console.log(board)

     </script>

1 Like

Looping a triangle

           var rowsInTotal = 7
           for(firstRow = 0; firstRow < rowsInTotal; firstRow++){
              var numTag = "#";

             for(tags = 0; tags < firstRow; tags++){
               numTag += "#";
             }
             console.log(numTag);
           }

FizzBuzz

      var i = 1
      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);
        }

      }

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

triangle loop

for (let line = "#"; line.length < 8; line += "#")
  console.log(line);

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

Edit by @gabba

1 Like

Hi guys, need some help with the fizzbuzz. Checked my code many times, compared to different sources and it looks that it should be executed, but when I try it in console, I get an error about “else” command “Uncaught SyntaxError: Unexpected token ‘else’”. Tried both Brave and Chrome. What is the issue?
Screen Shot 2020-05-02 at 21.16.21

Have an issue with triangle as well. I write the code which executes as a perfect triangle in the books code sandbox, but in browsers console I get this “website.html:61 Uncaught ReferenceError: line is not defined at website.html:61”.

My code: for (let line = "#"; line.length < 8; line += "#"); console.log(line);
Do you have any idea why different consoles give different answers and how should I define that line?
@ivga80 maybe you can help here, as I was struggling quite a lot with chessboard too, finally got the code into the place, and again, browser’s console give me an error “Uncaught SyntaxError: Unexpected token ‘else’”, while it executes on books code sandbox. What am I doing wrong?

 for (let number = 0; number <= 100; number += 1) {
	let output = "";
	if (number % 3 == 0 ){
		output += "fizz";
		
	}  if (number % 5 == 0){
		output += "buzz";
		
	} if (number % 3 == 0 && 5 == 0){
		output += "fizzBuzz";
	} else {
		console.log(output || number);
	}
}
let Bsiz = 8;
        let board= "";
        for(let y = 0; y < Bsiz; y++){
          for(let x = 0; x < Bsiz; x++) {
            if((x + y) % 2 == 0){
              board += " ";
            } else {board += "#"}
          }
          board += "\n";
        }
  console.log(board);

Edit by @gabba

Find the difference from your foto with this one i corrected. It’s small differnce but i think this is why you get the uncaught syntaxerror. And you could leave {} for consoles. Scroll up you will find your answers too. Learning languages is testing and testing and testing and sleep and then again, test ,test ,test, sleep and again … :nerd_face: :sweat_smile:

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

at the triangle you make the same thing :wink: :sunglasses:

for (let line = "#"; line.length < 8; line += "#") console.log(line);
1 Like

Thanks a lot, need to study how to use semi colons :slight_smile:

I am not a programmer, i am only a student like you, the only good for me is that i have had some prehistoric touch with html(2006-08) and javascript later until 2013 helping friends with webpages in Greece, so it was easier to jumb on board again but still learning new things every day.
At first semicolons were important and in the book it says it is good to learn to apply them. But this doesn’t mean that after everything there comes a semicolon. Semicolons come after an expression or a statement or to grasp a value, not after the function type.
Unfortunatly we have to understand what we want to write(depending the problem we have) and how we have to express it(so javascript understands it). So if i break the code for triangles :
function() is all this in your case for (let line = "#"; line.length < 8; line += "#") inside the () you have values that need ; so they are attached, but because after your function comes the expression console.log(line) this is which needs the semicolon at the end to work.
After some work and research as long as i am studying here i have found out, better let a semicolon away than to put more than needed, because of JavaScript’s Automatic Semicolon Insertion (ASI) . Basically, JavaScript will put semicolons in for you automatically if you leave them out. Here are some good links, i would suggest read the first one first and then the second. This explains you when needed https://news.codecademy.com/your-guide-to-semicolons-in-javascript/ and this is one of many that you can find and will see that is 50-50% if use or not and why https://medium.com/better-programming/you-might-need-those-semicolons-in-your-javascript-after-all-b28154f93ea8

2 Likes

FizzBuzz Problem:

 for (var i = 1; i < 101; i++){
          if (i % 15 == 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 Problem

let size = 8;
let 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);

Edit by @gabba , plz @DreamtGalactic use the preformatted text tag

1 Like

1. Triangle

var rowsInTotal = 7
for(firstRow = 0; firstRow < rowsInTotal; firstRow++){
var numTag = “#”;

         for(tags = 0; tags < firstRow; tags++){
           numTag += "#";
         }
         console.log(numTag);
       }

2. Fizzbuzz

for (var x= 1; x<=100; x++){

  if (x % 15 == 0)
    console.log("FizzBuzz");
  else if(x % 5 == 0)
    console.log("Buzz");
  else if(x % 3 == 0)
    console.log("Fizz");
  else console.log(x);

}

3. Chessboard

var even = " # # # #"
var odd = "# # # # "
row = 0
while(row<8){
if(row%2==0){
console.log(even);
row += 1;
}else{
console.log(odd);
row += 1;
}
}

1 Like
// Expanding Triangle Training Excercise
for (var x = "#"; x.length < 8; x += "#")
{
     console.log(x);
}
// Fizz Buzz Training Excercise
for (let x = 1; x <= 100; x++)
  {
    let output = "";
    if (x % 3 == 0) output += "Fizz";
    if (x % 5 == 0) output += "Buzz";
    console.log(output || x);
}
  // Chessboard Training Excercise
  for (var i = 0; i<8; i++) 
    {
      var chess = "";
      for (var n = 0; n<8; n++) {
      if ((i+n)%2 == 0) { chess+=" ";}
      else { chess+="#"};
    }
      console.log(chess);
  }
1 Like

Hello. Do you use document.write in place of console.log. I have spent hours getting console.log to work when I have it in an html file and open it with my browser(s). It works in the eloquent test environment and in the console, but not when placed in a area of an html. Just curious as I have wasted a lot of time figuring it out (a library I need ? A setting?). THANKS.

Hello. I have a question that I have spent hours on and have it posted elsewhere on the site.
I have my code working on the Eloquent Test Environment and on the console. Yet, specifically, the console.log() does not output when it is encountered by any browser (Brave/ Chrome/ Edge) within a script-wrapping html file.
I have spent hours trying to get console.log to work; of course I have worked around it (so far in my infancy of JS) – I have tried changing settings but cannot get console.log to work, although I know the vars are taking values by printing them with console(). And running it on console and in the Eloquent test environment.
Any ideas ? My advisor said to “learn to use the internet” – yet I have tried many search engines trying to figure it out (am I missing a library?) THANKS.

Hi Tara. Can you please post your code so we can take a look at it?

That’s correct, but it’s taken out of context. I said you should learn and get used to searching the resources (internet) available to you, because we developers often spend 40-60% of the time doing google searches. Google is a developers best friend. :wink: That was regarding your last question with the jquery issue…

If you post the code here, we will be glad to help you of course. :hugs:

Ivo

1 Like

do you copy&paste the code in your browser?
can try and see if you get different results if you copy&paste these two code snippets below.

snippet 1:

var line = “console.log will not work”;
console.log(line);

snippet 2:

var line = "console.log will work";
console.log(line);

result of snippet 1: will not work!

Result of snippet 2: Will Work!!

I hope this solves your issue. We have to try to type as much code as possible and don’t use copy&paste while practicing… type the code instead.:hugs:

Good luck.

The solution is shown in this image. I hope you have seen this posted in the forum before?

Ivo

1 Like

Hi @rodrigopacini

Almost there :wink: rodrigopanacini

With a small modification you could get the exercise right
rodrigopanacini

So you have to print a space when the number is even, and a # when the number is odd.
But you don’t have isOdd or isEven function available here.

I think you should look at the difference between this 2 operators it will help you to solve it
/ -> divide and % -> modulo

In this exercise we are using a trick to know if the number is odd or even
When you use the modulo ‘%’ the result is the remainder of an operation.

when you are dividing an Even number by 2 the remainder is always zero.
But you are looking for the remainder here not the result of the division.

In this part of the code you are using / and %
if (( contagem + count )/2 % 2 == 0)

This is not correct, i let you figure it out why :wink:

2 Likes

Tks Gabba! I’ll try to fix.

1 Like