Chapter 2 Exercises

Fantastic answer, my friend. This just turnet in to one of the resources for the new students. Congrats. :handshake:

Ivo

1 Like

Buff…Struggling exercises. Specially the chessboard one, for which I’ve seen some answers. Eventually I’ll tried to write it in my own style, eventhough there some things I still not understand at all. Why if I remove the first “Var to Print” the result is so crazy? I thought it was all specified enoght in the later code.

//Exercise Fizzbuss

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

if (number % 3 == 0) document.write("vh2> Fizz ");
else if (number % 5 == 0) document.write("vh2> Buzz ");
else document.write("vh2> “+number+” ");
}

//Chessboard

let theNumber = Number(prompt(“How large you want your chessboard?”))

for (var row=1; row<=theNumber; row++){
var toPrint = “”;

for (var col=1; col<=theNumber; col++){

  if (row%2==0 && col%2==0 || row%2!=0 && col%2!=0){
  	       toPrint+=" ";
            }
         else(toPrint+="#");
     }
      console.log(toPrint)
      document.write("vh2> "+toPrint+" v/h2>");
      	    }

Thanks a lot for the support. Credit to some guys in the comments above. Some of them helped me to understand it.

Hi,
The " " marks in your Number(prompt("")); are not right. Prompt will throw an error becase of that.
Try to move the var toPrint = “”; above the first for loop, and don’t forget the new line breaker towards the end of the code.

Make sure you open with < instead of v. This is all i have for you to help. I still haven’t figured out why the document.write doesn’t print a chessboard pattern on the web page itself. Hopefully someone else will reply about that.

Thank you Zoltan!

I’m doing it in Atom in a .html at the " "" " work. Now I see that for doing it directly in the console i should use" ' ' ".
What you said about the var toPrint and the line break it’s something to make the code looking better or implies a problem? It works. Just to know…I don’t understant at all i think…
"<vh2>" this is cause I check it in the web browser…

Here is my code FizzBuzz

  var input = "";
        var num = 1;

        // Variable that comes from the prompt input

        var stop = prompt("Count until...?", 100);
        var top = parseInt(stop) + 1;

        if ((top > 0) && (top % 1 == 0) && !(top==NaN)) {

          while (num < top) {
            if (num % 15 == 0) {
              input += "FizzBuzz<br>";
               num++;
             }
             else if (num % 3 == 0) {
               input += "Fizz<br>";
               num++;
             }
             else if (num % 5 == 0) {
               input += "Buzz<br>";
               num++;
             }
             else {
               input += num + "<br>";
               num++;
             }
           }
        }

         // Printing result in the page

     console.log(input || num);

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

document.write(board);
1 Like

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;
        }
      }
2 Likes

Hi. You need some \n to break take lines in your code.
As it is the document.write() only prints out a line of ##.
You will have to put something more to break the lines in your code.

Or just change it to console.log instead.

Ivo

Hello all,

Can someone please explain me, why I create an infinite loop while using a certain code for the first exercise (Looping a triangle)?
The first code I use, doesn’t create an infinite loop. However, the second one does. In my opinion the second code is similar to the first one, only adding something extra.

Clean loop

var a = '#';
for(a.length; a.length<8; a+='#'){
    console.log(a)}

Infinite loop


var a = '#';
for(var b=a.length; b<8; a+='#'){
    console.log(a)}
1 Like

Fizzbuzz:

Fizzbuzz

Chessboard:

Chessboard

Hello Everyone,
:face_with_head_bandage:So I’m sitting on this day two now and I’m trying to apply logic in to all this in order to understand the actions behind it . I have read most of peoples answers and I’m getting the grip on reading it and someway understanding … I don’t want to simply fly thru this by using someone else solution . I wan to understand it … Please share and links that can help apply logic to our actions?
Any help is greatly appreciated. :love_you_gesture:

2 Likes

PTO @P.T.O I just solved this exercise. I understand your feelings: we want to solve every single exercise by ourselves and feel totally empowered !! In this case, I think it’s tricky !! I found two solutions after thinking for a while. I will comment both solutions below. One is a dumb solutions, or like a very easy to understand, but it uses a lot of code. Then, a second solutions is better because it is very succinct !! In any case, my recommendation is NOT to proceed to think about this exercise if you are NOT SUPER SURE about how to use one single FOR LOOP. As you will see, you can use one single For Loop to apply a set of instructions (some lines of code) to a series of values. You can imagine this as one single row of people seating in one single line of chairs waiting to be called for an audition. The For Loop goes, one by one, chair by chair, performing a task with each person in his/her own chair. This is easy, because it is a LINE. One line = 1 dimension… In this case, however, it is not a 1-dimensional row. What we have here is a two dimensional pattern (a matrix), more like a movie theater with many rows. In the matrix, then, you have rows and columns… That’s why we use 2 For Loops !! You use the first For Loop to represent the counting of positions in the rows, and the second For Loop to represent the counting of positions in the columns !! When you mix both, you can localize any position inside the two dimensional matrix. Like in a real movie theater, you can go to the first row, in the front, and number each seat, one by one, as 0-0, 0-1, 0-2, 0-3, 0-4, etc (the first digit is the number of the position in the the row, and the second one is the number in the column). The second row would look like 1-0, 1-1, 1-2, 1-3, 1-4…, etc… The third row would be 2-0, 2-1, 2-2, 2-3, 2-4… etc… And so on… We must apply this principle !! We represent the rows with the first For Loop, and the columns with the nested For Loop !! When you nest the second For Loop inside the first one, and you add your code inside the second Loop, then, your instructions will be applied, one by one, to each position in the entire matrix ==> one by one !!! Therefore, the key here is to be very clear on how to use one single For Loop first, and then how to use a For Loop nested inside another For Loop !!!.. Sorry, about the long text :)!!! I wish you a lot of luck !!

1 Like

2 Likes
// 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);
}

Uses the for() conditional keyword, initializes the variable n to 1, and sets the iterations frequency determinate and a increase counter variable, then inside the for statement, rests an initialized variable named output and 2 other if() conditionals which use modulus division to determine output of “Fizz” or output of “Buzz”.

The result is then console logged console.log() out to the terminal.

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

Same idea but just with the size

1 Like

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

(Chessboard)
lets pair="#####";
let impair="####";
for (let I=0;i<8;i++){
if(I%2==0){
console.log(pair);
}else{
console.log(impair);
}

}

1 Like

Hi Glen,
Thank you for your inside . I’m digging all over :earth_americas: and getting better understanding on how everything works . Its a little frustrating that I’m watching other people tutorials instead learning with this course. Anyway I will figure this out . But I haven’t fell that dumb in years :rofl:

4 Likes

@P.T.O Man, yesss! In deed! The exercises are very challenging!! I started two days ago, and I am investing literally all day long! I barely sleep now :laughing: :sweat_smile: I am doing every single exercise with Ivan, one by one. I am also reading every single line of the book and doing the exercises from the book. But, I still need to check other sources ofc !!! With every step…, with every lesson…, you can feel your neurons firing at high speed !! Literally the brain has to work at maximum capacity in order to code !! Haha I am enjoying this crazy ride so much. But, it’s tough !!! Let’s keep fighting :muscle: Best wishes :muscle:

4 Likes

Looping a triangle

var a = '#';
for(a.length; a.length<8; a+='#'){
    console.log(a)}

FizzBuzz

for(n=1; n<101; n+=1){
    if ((n%3 || n%5)==false){console.log('fizzbuzz')}
    else if (n%3==0){console.log('fizz')}
    else if (n%5==0){console.log('buzz')}
    else{console.log(n)}
}

ChessBoard

If you modify the value of x you will get the pattern modified on both axis.

x=8;
var a=' #';
var b='# ';
y=1;
while(y<=x){
   if(y%2==0){for(a.length; a.length<x; a+=' #'){}
   console.log(a)}
   else{for(b.length; b.length<x; b+='# '){}
   console.log(b)};
   y=y+1;
 }
1 Like

Looping a triangle

var initialString = "#"

      for (var row = 0; row < 7; row++){

        console.log(initialString);
        initialString += "#";

      }

FizzBuzz

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

            console.log("Buzz");

          }
          else {

            console.log(number);

          }
        }

Chessboard

    var size = 8;         //change size to required value
    var chessboard = "";

    for (var row = 0; row < size; row++ ){

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

        if ((row+col) %2 === 0){

          chessboard += (" ");

        }
        else {

          chessboard += ("#");
        }
      }
      chessboard += ("\n")
    }

    console.log(chessboard);
1 Like

I have been researching this for hours now. Headache.
Been reading all your answers and trying to figure out.
I guess I am lost but I think I will get it.
Being truthful here.

3 Likes