Chapter 2 Exercises

Hi @val4o,

Nice solution for FizzBuzz :ok_hand:

When the inner for loop exits (at the end of each row) "\n" adds a line break, so that the next iteration of the outer for loop can start the new row on a new line. You can read more about it in this post.

Also, I’m not sure if you know, but before you type in your code to post it here in the forum, click on the </> icon in the menu at the top of the text editor. That will give you 2 sets of 3 back ticks…
```
```
If you now input your code between these, you will end up with it nicely formatted. You will probably still need to organise it a bit more with the correct spacing and indentation etc., but it’s much easier to do that effectively once it’s formatted than when it’s not. It also helps spot any errors, as the code is much clearer and easier to read. Your code for FizzBuzz should end up looking something like this…

for (let x = 1; x <= 100; x++) {
   if (x % 3 == 0 && x % 5 == 0) {
      console.log('FizzBuzz')
   }
   else if (x % 3 == 0) {
      console.log('Fizz')
   }
   else if(x % 5 == 0) {
      console.log('Buzz')
   }
   else console.log(x)
}
2 Likes

Nice work @Kingsman! :ok_hand:

I’m not sure if you know, but before you type in your code to post it here in the forum, click on the </> icon in the menu at the top of the text editor. That will give you 2 sets of 3 back ticks…
```
```
If you now input your code between these, you will end up with it nicely formatted. You will probably still need to organise it a bit more with the correct spacing and indentation etc., but it’s much easier to do that effectively once it’s formatted than when it’s not. It also helps spot any errors, as the code is much clearer and easier to read. Your code for Chessboard should end up looking something like this…
(My notes show where I made changes to your code for an error and improvements)

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 += " "; // curly brackets not needed
      else board += "#";                  // curly brackets not needed
   }
   board += "\n";  // 'Board' changed to 'board' (upper/lower case matters)
} 

console.log(board);
1 Like

Hey @kmilo_Mart,

That’s great that you want to do it with as little help as possible :muscle:
Have you already tried looking at the hints in the online version of the course book? They are hidden, and you can choose to display them by clicking on Display hints (in blue) below the exercise instructions.
Those would be the best starting hints, if you haven’t already tried them. If they aren’t enough, let us know and we’ll give you some more.

There are also some YouTube videos where people write the code to these actual exercises, step by step. You don’t have to watch these all the way through to the final solution straight away. You could just watch the start to get you going, then try to continue yourself… watch a bit more if you get stuck…continue… watch a bit more if you need to… etc. etc.

2 Likes

Hi @jpc,

Your code is correct, and it works when I run it in the console.

Maybe you’re having an issue with when you press the return/enter key. Let me explain:

  1. Type in your variable let number = 0;
  2. Press return/enter.
  3. You will see it returns undefined because you’re only declaring a variable, but don’t worry the value is now assigned to that variable name. If you prefer to see the variable value returned, then just enter number = 0; without the keyword let, instead. That will work too, and the value is still assigned to the variable name number.
  4. Now type in your while loop. To get the separate lines (before entering the statement) you need to press shift + enter/return… I think this may be your problem.
    You can also just type the whole loop on one line like this:
    while (number <= 12) {console.log(number); number = number + 2;}
    That will work just the same, but personally I prefer to see my code with indentation on separate lines, as I find it easier to see what’s going on and organise my thoughts.
  5. Then, when you’ve entered your closing curly bracket, press enter/return.
  6. You should now see all of the values for each loop logged to the console (from 0 up to and including 12) :partying_face:
    AND the current value stored in your number variable is also returned, which is 14 not 12. It was increased to 14 at the end of the final loop, but wasn’t logged because the condition at the start of the next loop failed:
    14 <= 12   // => false

Let us know if this solves your problem, or whether it’s something different.

2 Likes

I’m on my way to get the logic of the code, I’ll have a look of the book’s hints
Thanks

1 Like

When im on atom and i type a function its not coming up in color does anyone know how to solve this??

1 Like

FizzBuzz

After first try came up with this:

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

Chessboard

This was harder for me and had to peek for a bit:

    var board = "";
    var size = prompt("Boardsize? (Enter a number)");
    for (var row = 0; row < size; row++) {
      for (var col = 0; col < size; col++) {
        if ((row+col) % 2 == 0) {
        board += "#";
        }
        else {
        board += " ";
        }
      }
      board += "\n";
    }
    console.log(board);
1 Like

Ive tried to do the looping triangle this is the what i put :

for ( var i = #; i.length< 8 ,i++) { console.log ("#");} when i try to execute nothing happens just a blank page.

Hi @jon_m,

Okay I’ve edited a few things after reading your feedback and I think I have it now!

for(counter = 0; counter<100; 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)
        
       }
2 Likes

Hi again @jon_m,

My first attempt at the triangle is below… I believe it works but it’s obviously ridiculously long… :joy:

var hash = "#";

      for(var counter = 0; counter<1; counter++){
          document.write(hash);
          }
      document.write("<br>");
      for(var counter = 0; counter<2; counter++){
          document.write(hash);
          }
      document.write("<br>");
      for(var counter = 0; counter<3; counter++){
          document.write(hash);
          }
      document.write("<br>");
      for(var counter = 0; counter<4; counter++){
          document.write(hash);
          }
      document.write("<br>");
      for(var counter = 0; counter<5; counter++){
          document.write(hash);
          }
      document.write("<br>");
      for(var counter = 0; counter<6; counter++){
          document.write(hash);
          }
      document.write("<br>");
      for(var counter = 0; counter<7; counter++){
          document.write(hash);
      }

I’ve done some more research on .length and noticed that it only prints characters and not numbers. I’ve also practiced the column/row example a couple of times.

Chessboard
I have read through other posts like you suggested and it is starting to make sense.

1 Like

Will only post Chessboard. FizzBuzz and Triange I have already encountered before

Chessboard:

let white = ’ #’

let black = "# "

let i = 1

let size = 24

while (i <= size) {

if(i % 2 === 0) console.log(black.repeat(size / 2));

else console.log(white.repeat(size /2 ));

i++

}

1 Like

Well done, @pascaldeb! I can see you’ve really worked hard at this :muscle:

Now let’s think about taking Chessboard to the next level:

Your code works fine with dimensions 8 x 8 (8 rows, 8 columns). However, let’s say you wanted to provide the flexibility to change those dimensions to say 10 x 10, or 5 x 5. With your version, each time you’d have to manually amend:

  • the number of '#'s in your two variables evenRow and oddRow; and
  • the row count limit in your for loop condition: i < 8

Rather than have to make these manual adjustments each time, we ideally want the program to be able to handle this by a simple variable reassignment.

You could adapt your program to do this by declaring an additional variable at the beginning which stores the row limit, and then replace the fixed 8 with this new variable’s name in the for loop condition.

The problem then becomes how to extend this functionality to the number of columns as well. Have a look at how the model answer deals with this (using two for loops, one nested within the other). You will really learn loads by spending time at this “reflection stage”, and by trying to amend your own version for this additional functionality.

By the way, watch your spelling — it doesn’t matter if your spelling is “original” as long as it’s consistent: you currently have both bord and board, and so it throws an error.

Keep on learning, you’re making good progress! :muscle:

Excellent solutions, Luis! :star2:
… and great formatting :+1:

1 Like

🤨 ,my sats aren't stacking? Nor my "#"s


my code looks like this

``` for (row ="sats"; row.length < 8; char += "sats"){ console.log(row); } ```

Sats should be stacking but when i run it all I get is the same code or error undefined 😑

Thanks in advance for the help

Fresh
1 Like

Hi @Mujtahid_Haque!

:partying_face:
Well done for persevering! :muscle:
You will have learnt loads by turning it over in your head, researching, then thinking about it again until it clicked — instead of giving up sooner and looking at the model answer. You’ll find that they were 3 days well invested!

Some feedback about your solutions:

  • All you solutions execute successfully :+1:

  • A nice original alternative solution to Looping a Triangle :+1:

  • You don’t need the 2nd comparison in the 2nd and 3rd if statements, because you’ve already ruled these out in your 1st if statement (so they will always be true). So you can simplify them to:

    else if (count % 3 == 0) {...}
    // and
    else if (count % 5 == 0) {...}
  • I would add more spacing between your values and operators, as it makes the code easier to read e.g.
for (count = 1; count <= 100; count++) {
   if (count % 3 == 0 && count % 5 == 0) {...}
   ...
}

Otherwise, your formatting is excellent! :smiley:

1 Like

Hey, Fresh!

Your sats aren’t stacking, nor looping the loop, because you’ve suddenly switched to an undefined variable name in your final expression (the one that increases your sats by +1 each loop):

row = "sats"   :+1:
row.length < 8;  :+1:(0.5)
char += "sats"  :x: (you’ve randomly switched from row ⟶ char)

AND

… because you’ve got 4 characters in your string "sats" you already have row.length === 4; for row 1.
So you need to increase your exit condition by x4…so you can keep stacking during 7 loops.

Good luck :muscle:

1.for (let i = “#”; i.length < 8 ; i += “#”)
console.log (i)

  1. for( let counter = 0; counter <100 ; counter++)
    { if ( counter %3 === 0 && counter %5 === 0)
    console.log ( counter + “fizzbuzz”)

else if (counter %3 ==0)

console.log (counter + “fizz”)

if (counter %5==0)
console.log (counter + “buzz”)
}

Can anyone tell me why all the numbers arent printing out with this??
it only prints out numbers %3 and %5

Chess board
for ( let i= 0 ; i < 8 ; i++)
console.log(i+ “# # # # # # # #” )

Similar issue with this one the chess board prints but there is numbers next to it.

1 Like

Great solutions @daz3d!
…especially your use of the pop-up prompt and <table> elements in Chessboard :star2:

Unfortunately, your Chessboard only prints the right pattern with even numbers…I’m not sure if you’ve noticed this and are already working on a solution :wink:
If not, try entering a parameter of 8, then 9, and you’ll see what I mean.
Would be great to see how you resolve this with the same table method.

1 Like

Hey @matthurd,

Check out this topic it’s all about your issue.

Let us know if this doesn’t sort the problem.

Hi @matthurd,

  1. You need to put your # in quotes in the variable declaration as well, because it’s a string: var i = "#";
  2. You need a semi colon instead of a comma after your condition in the for loop header: i.length < 8;
  3. Your iterator variable (var i = "#") isn’t a number, it’s a string, so i++ won’t work. You need to add an additional "#" each time. To do that you need i += "#" as your final for loop expression (that’s a more concise way of writing  i = i + "#" )
  4. You need to log your variable to the console on each iteration, not a fixed "#". Otherwise you will just be printing rows of 1x# and not ever longer ones.
  5. Before you’ve loaded the document in the browser, you need to make sure you’ve saved your latest version in Atom.
  6. I assume that once you’ve loaded the document in the browser, you’ve opened the console — the code in this exercise is logging to the console, and not writing to the document.

Let us know if, after addressing all of the above, you still have a problem.