Chapter 2 Exercises

Hi, Try to change console.log(); to document.write();
It should work like this:

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

Ivo

1 Like

Woow haha it worked, thanks. I feel so dumb right now. How did I not see that? lol

2 Likes

Is it only me who couldn’t solve the chessboard? I have spent the whole afternoon trying to solve it, but didn’t get anywhere with this one.
I feel like this course is a bit hands off. Need more explanation on what’s what and why.

1 Like

Exactly! I was struggling with the Chessboard too. I don’t feel like we are well taught how to think efficiently, in order to be able to solve that exercise. Maybe I am dumb, but this course was advertised for anyone without any kind of programming experience. @ivan @filip

2 Likes

Ok I tried a lot, but could not get by myself, or actually I because as an developer google is my best friend…This solution was one of many, but I like the layout.

var chessBoard= " ",
size = 8,
c;
for(var i = 0; i < size; i++) {
c=i%2 ? ‘# ’ : ’ #’;
for(var j = 0 ; j < size/2; j++){
chessBoard+= c;
}
chessBoard+= ‘\n’;
}
console.log(chessBoard);

1 Like

Hi Zoltan.
Please spend some time reading the posts above. A lot of people struggle with this first exercise, But we all got trough and its hard for a reason, my friend.
Just hang in there and use the resources available to you.
Hint, hint. There is no need to reinvent the wheel, just don’t copy&paste code from others, type it yourself and try to understand why it’s done like it is.

I hoped it helped you a little on your way.

And yes, you can learn this as a non-programmer, Just ask the people at the end of this course. I’ll link you the topic and you can ask those people if any of them knew how to program before they started.
Here you go, ask them in this post, maybe their answers can get your motivation up? :wink:

Ivo

2 Likes

Thanks Ivo, you are right, I’ll push more.

1 Like

Chessboard

By including a for loop inside of another for loop, we are iterating through the numbers added to the column variable. Running the second for loop( let’s call it “column loop”), generates a number 1-8. Each of these numbers then are added to the number generated by the first for loop (let’s call it “row loop”). The initial number that is generated by the “row loop” is 1. That number then is iterated through the numbers generated by the “column loop” and checks if % 2 == 0 to give a True value(if the number is even) or a False value (if the number is odd). If the Boolean is True, it will print “ “ to the console, if it’s False, it will print “#”.
When the number of iterations reach 8, the ‘board += “\n”;’ executes onto a new line and exits the “column loop”, and adds a number(row++) to “row”. At this point row will be equal to 2. We are entering into another iteration through the “column loop”, but as this time the row is set to an even 2, adding the first column number which is 1 to it, will produce an odd number % 2 == 0 will return False, so the new row will be starting with “#”.
This iteration continues until the “row loop” returns False, meaning, not less than or equal to the size variable.

1 Like

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