Chapter 2 Exercises

We on our way!🤑

This has been a mission. Still need to reread and prolly go through the Ivan lectures again BUT we got success!

I'm sure there's a sexier way to get those spaces where I want them but hey🤷🏾‍♂️ it works!

`let n = 0;

while (n <=99) {
n = n + 1;
let output = “”;
if (n % 3 == 0) output += “stackn”
if (n % 5 == 0) output += “sats”
if (n % 5 == 0 && n % 3 == 0) output += “whale_status”
console.log(output || n);
}`

Still wrapping my head around the power of logical or...really operators in general and why exactly does it start at 2 if n=1. I assume because 0 is the 1st integer counted and so is actually 1. Technically 0 = 1 and or -1 (which is still 1 right? Anyway...)

Shout to all you code ninjas out there I have a SERIOUS new found respect for yuh craft. 💯

as alwaysTeamwork Makes The Dream Work &

🤑KEEP STACKN THOSE SATS!


Fresh OUT!
waite one more Q, what else can one put in place of "" in line 4 and still get to "whale_status "?(yes it's a bit jumbled but progress is a process, no?)
1 Like

Triangle

var toPrint = “”;
for ( var i = “#”; i.length <= 7; i += “#”){
toPrint += “#”;
document.write(toPrint + “
”)
}

FizzBuzz

for ( i = 1; i <= 100; i++){
if ((i % 3 == 0) && (i % 5 == 0)){
document.write(“FizzBuzz” + “
”)
}
if (i % 3 == 0){
document.write(“Fizz” + “
”)
}
else if (i % 5 == 0){
document.write(“Buzz” + “
”)
}
else {
document.write(i + “
”)
}
}

Chessboard

var num_row = 8;
var num_col = 7;
toPrint = “”;

      for (row = 0; row <= num_row; row++){
        for (col = 0; col <= num_col; col++){
          if (row % 2 == 0){
            if (col % 2 == 0){
              toPrint = toPrint + "&nbsp";
            }
            else {
              toPrint = toPrint + "#";
            }
          }
          else {
            if (col % 2 == 1){
              toPrint = toPrint + "&nbsp";
            }
            else {
              toPrint = toPrint + "#";
            }
          }
        }
        toPrint = toPrint + "<br>";
      }
      document.write(toPrint);
1 Like

Hi @pabnan,

Your code runs successfully if you add the missing closing curly brace.

Always format your code when posting it here in the forum. This will make it easier to spot errors and slips like the missing curly brace, because the code is much clearer and easier to read. Before you add your code, click on the </> icon in the menu at the top of this forum’s 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. Your code for FizzBuzz should end up looking something like this…

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

Notice how I’ve simplified your conditional execution by replacing your nested if...else statements (which are hard to read and follow) with else if statements. You can also remove a lot of the brackets, and you should use more spacing, both of which also makes your code much clearer and more readable.

Thanks jon for the pointers

1 Like

Great coding @Emmerich! :smiley:

I can see that you’ve really worked hard at this… especially Chessboard ! :muscle:
Well done, for persevering!

All of your code executes perfectly, but I will just address the points you raised about Chessboard:

Your solution works well, and is a valid alternative. The model answer is never the only way.


You can use  "&ensp;"  to print the space. HTML will recognise this as whitespace of a certain size. The following link is to a list of Named Character References supported by HTML, in the WHATWG HTML Living Standard:

https://html.spec.whatwg.org/multipage/named-characters.html#named-character-references


Unlike document.write() , each  console.log()  statement will log its output to a separate line in the console. So what you need to do is create a separate variable to build up a string of hashes and spaces, which you can then log to the console either (i) at the end of each row (without the need for "\n") or (ii) at the very end of the program, on completion of both for loops (which does require a line break to be added to the string at the end of each row, with "\n").

See if you can now get it to work using console.log() :slightly_smiling_face:

Keep on learning…you’re making great progress!

FizzBuzz

<html>

  <head>
      <title>this is FizzBuzz</title>

  <script>

for (var num = 1; num <= 100; num++){
  var word = ""
  if (num % 3 == 0){
    word += "Fizz";
  }
  if(num % 5 == 0) {
    word += "Buzz";
  }
  console.log (word || num)



}

  </script>


  </head>
    <body>

    </body>





</html>

chessboard

<html>

  <head>
      <title>this is Chess</title>

  <script>

var size = 8;
var board = "";
  for (var x = 0; x < size; x++){
    for (var y = 0; y < size; y++){
      if((x+y) % 2 == 0){board += " ";}
      else board += "#";

    }
    board += "\n";
  }
  console.log (board);

  </script>


  </head>
    <body>

    </body>





</html>
1 Like

Hey @Kraken!

This is a great variation on the course book exercise! :ok_hand:

I really like how you’ve got the chessboard looking squarer, by increasing the number of hashes and spaces for each individual square :+1:

The problem you’re experiencing with document.write() is the fact that HTML won’t recognise a space keyed as the first character of a string, and will only recognise single spaces keyed at any other position in the string. This can be resolved by using named character references supported by HTML for different lengths of whitespace e.g. &ensp; or &emsp; (the second is longer)
So you can experiment with different combinations to get your preferred length of whitespace e.g.

"&ensp;&ensp;&ensp;"
// or
"&emsp;&emsp;"
// or
"&ensp; &ensp; "
// or
"&emsp; &ensp;"
// etc.

Note that single keyed spaces after the initial character will be recognised and will increase the overall length of the whitespace.

This obviously means that, in your program, you’ll need to handle logging to the console separately from displaying on the web page. Anyway, have a play around and experiment, and see what you can come up with :slightly_smiling_face:


The following link is to a list of Named Character References supported by HTML, in the WHATWG HTML Living Standard :

https://html.spec.whatwg.org/multipage/named-characters.html#named-character-references

Thanks for your help!

Looping a Triangle
Using less variable, it’s a great improvement.

Chessboard
str += "&nbsp "; it’s wouldn’t change the anything on web page output. it’s, on console, different.

1 Like

Hi @Ernest_SG,

Sorry for the delay in getting back to you on this.

Yes, if you were a complete beginner, then these exercises are a real challenge! You are definitely taking the right approach by going back over the material several times, and supplementing this course with other materials and courses is very sensible. You need to find the right mix and balance that works for you.

If you started this course as a complete beginner, it’s perfectly normal, and to be expected, that you will need to look at the solutions at some stage before being able to complete it yourself. As long as you give it your best shot first (which it definitely sounds like you have!) That’s the most important thing — to really spend time wrestling with it yourself first. Then, if you had to get some help, before moving on, make sure you analyse the solution(s), and kind of work backwards from there. This is a really important stage in the learning process. You can learn a lot by working out what the solution does differently and how to go about “bridging the gap” from what you managed to do (or not) on your own. As long as you understand the code you’re finally posting, that’s job done! :slightly_smiling_face:

Another good learning technique to use is to then try the exercise again from scratch without looking back at the answer (like a memory test). You can also try to do this after having left it for a certain period of time (say, the next day, then after a few days, then a week etc. etc.) This builds up longer-term retention.

Exactly! You’ve got the idea…and remember:
— “No pain, no gain!” :muscle:

1 Like

Hi @Maya,

Sorry for the delay in getting back to you on this.

You’ve made a great attempt, and I can see that you’ve worked hard at these exercises! :+1:

Looping a Triangle

To get it to work with document.write() you just need to add a line break HTML tag to each row of hashes, so that the next row is printed on the next line.

document.write(toPrint + "<br>");

Your other document.write() (to display the row number) also now works; although I would start the first loop with  var row = 1  so that the first row is displayed as “row number 1” (instead of “row number 0”). You also then get the 7 rows (not 8) that the exercise asks for.

You didn’t need to add the <br> tag with console.log() , because each time it is called it automatically logs to the next line in the console.

FizzBuzz

You have some problems with the flow of your conditional execution:

  • For numbers divisible by 3 only, and numbers divisible by 5 only, you are printing both “Fizz” or “Buzz” AND the number.
  • For numbers divisible by 3 AND 5, you are printing “Fizz” AND “Buzz” AND “FizzBuzz”.

Instead, you should be always printing EITHER “Fizz”, OR “Buzz”, OR “FizzBuzz”, OR the number.

You have all the Boolean expressions coded correctly, you just need to look again at:

  1. The actual control flow directed by the keywords if and else (and you also need to use else if) so that only one statement is executed for each loop.
  2. The order of the conditional statements, which is also important.

Have a go at resolving this yourself, and let us know if you need any more help.

Chessboard

Yes, these exercises are a real challenge!

That’s fine, and actually what you should be doing if you’re not sure how to solve it on your own. It’s also fine if you need to take a look at the solutions before being able to complete it. As long as you give it your best shot first. That’s the most important thing — to really spend time wrestling with it yourself first. Then, if you had to get some help, before moving on, make sure you analyse the solution(s), and kind of work backwards from there. This is a really important stage in the learning process. You can learn a lot by working out what the solution does and how it does it, and also how to go about “bridging the gap” from what you managed to do (or not) on your own. As long as you understand the code you’re finally posting, that’s job done! :slightly_smiling_face:

Another good learning technique to use is to then try the exercise again from scratch without looking back at the answer (like a memory test). You can also try to do this after having left it for a certain period of time (say, the next day, then after a few days, then a week etc. etc.) This builds up longer-term retention.

Keep on learning! You’re making great progress! :muscle:

Hi @Yuanming,

Good solutions :+1:

Did you arrive at them all by yourself before looking at the model answers? If so, really well done :muscle:

Just a few additional comments:

Don’t forget closing curly braces: you’re missing one in the first exercise (or you need to remove the opening curly brace).

Always format your code when posting it here in the forum. This will make it easier to spot errors and slips like the missing curly brace, because the code is much clearer and easier to read. Before you add your code, click on the </> icon in the menu at the top of this forum’s 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.

Have a look at some of the pre-formatted code posted by other students to see how it looks.

In your FizzBuzz for loop header, you have the number 1 assigned to the iterator variable as a string. This doesn’t actually throw an error, as I think num++ coerces it to a number value automatically from the 2nd loop onwards. But it’s good to get into the habit of storing the appropriate value type for the operations we want to perform with the value, otherwise this could lead to a bug during any further development of the program.

let num = 1;

Hi @Stas_Simon,

Good solutions :+1:

Just a few comments…

To format your code before posting it here in the forum, click on the </> icon in the menu at the top of this forum’s text editor. This 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, which is then also easier for you to organise with the correct spacing and indentation etc. It also makes it easier to spot any errors or copy-and-paste slips. For your Chessboard you should end up with something like:

let x = 8;
for (let i = 1; i <= x; i++) {
   let text = "";
   for (let j = 1; j <= x; j++) {
      if ((i + j) % 2 == 0) text = text + " ";
      else text = text + "#";
   }
   console.log(text);
}

Have a look at where I’ve added spacing and indentation in your code. It’s not mandatory, and some spaces are just down to personal style, but a lot them are good practice as it makes the code easier to read and follow.

Also, notice I’ve added the keyword let to two of your variable definitions. Get into the habit of declaring your variables with one of the keywords let , const or var . Then you can gradually start to understand why, and the differences between each of them.

Also, be careful to consistently use the right quotes: " and not “
I had to change the incorrect ones to get your code to run successfully.

Keep on learning! …you’re making good progress!

Will need to go over these until I can do them without heavy research

**looping a triangle**
  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);
  }

  **FizzBuzz**
for (var n =1; n<+100; n++){
  var output = "";
if (n % 3 == 0) output += "Fizz";
if (n % 5 == 0) output += "Buzz";
 console.log(output || n);
}

**chessBoard**
var num = 8;

var chessBoard = "";

for (let y = 0; y < num; y++) {
  for (let x = 0; x < num; x++) {
    if ((x + y) % 2 == 0) {
      chessBoard += " ";
    } else {
      chessBoard += "#";
    }
  }
  chessBoard += "\n";
}

console.log(board);
1 Like

Hi Fresh!

First of all … love this version :star_struck:

Yes!.. and that’s the main thing…well done! :muscle:

Still, good to see you really thinking about what the code is doing, looking to make improvements, and asking questions… so let’s see if we can answer some of them for you…

If you’re referring to putting spaces between “stackn sats whale_status”, you can achieve this by simply adding a space to the end of the first two strings:

output += "stackn "
output += "sats "

:open_mouth: :thinking: :no_mouth: You’ve lost me there, to be honest… :wink:

You don’t need to add the line  n = n + 1;  if you assign 1 to the variable n in the first place (instead of 0). As we are counting and printing numbers (or their word replacements) from 1 to 100 (not 0 to 99), then that makes more sense. We would then also need to change our condition to n <=100 

output || n

This Boolean expression is evaluated from left to right:

  • output is initially declared as having an empty string ("") assigned to it. An empty string evaluates to the Boolean false. This means that if all 3 of the conditions in the if statements evaluate to false (this will happen for numbers which aren’t divisible by either 3 or 5) then output will remain as an empty string and in this final Boolean expression will evaluate to false.
  • If the first operand (value) of the logical OR operator evaluates to false , it will then move on to evaluate the second operand: in this case n
  • In each loop n = the number being “processed” in that loop (from 1 to 100). Because n always has a number >= 1 assigned to it, it will always evaluate to true, so if the final Boolean expression being logged to the console evaluates output as false, the expression as a whole will still always evaluate to true based on the number assigned to n for that particular loop, and so this number will be logged to the console.
  • In contrast, for all numbers divisible by 3 or 5 or both, the if statements will assign output a string of words, meaning that output will ultimately evaluate to true, the final Boolean expression being logged to the console will evaluate to true based on the string assigned to output, and that string (instead of the number) will be logged to the console…

… you still with me? :sweat_smile:

Having explained how output || n works, you should now be able to see why we need the line let output = "";

The alternative is to remove this line, and instead use an if ...else if ...else if ...else conditional execution, with each statement containing its own console.log() , each one logging one of the four different possible outcomes whenever its associated condition evaluates to true: EITHER “stackin”, OR “sats”, OR “whale_status” OR the actual number.

Continue to play around with your code, and experiment with the alternative method I’ve mentioned. You’ll learn loads by doing that.

Keep on coding with such great creativity… and keep on asking questions! …you’re making great progress! :smiley:

Hi @alex.k,

You’ve made really good progress with these :ok_hand:
…now lets add the finishing touches…

Make sure you format all of the code you post here in the forum (just like you did with most of your code for Chessboard). This will make it easier to spot any errors or copy-and-paste slips. You can clearly see from the difference between the formatted and unformatted code that you’ve posted, that the formatted code is much easier to organise in terms of spacing, indentation and positioning of brackets etc… and is also much clearer and easier to read.

Unfortunately, the code you’ve posted doesn’t execute successfully because it contains incorrect quotes ( “ instead of " ), and your Looping a Triangle and FizzBuzz contain line breaks within the strings you are attempting to display on the page using document.write().

The formatted part of your Chessboard code has the correct type of quotes and you’ve used + "<br>" to achieve the line breaks. So, I’m not sure why you haven’t done this throughout all of your code i.e.

// Looping a Triangle
document.write(toPrint + "<br>");

// FizzBuzz
document.write("FizzBuzz" + "<br>");

Your FizzBuzz also prints both “FizzBuzz” and “Fizz” for numbers divisible by both 3 AND 5. This is because the conditions of both the first and second if statements are always evaluated, even if the first condition evaluates to true and executes the first statement. This can easily be corrected by making the second statement else if — this makes all 4 conditional statements mutually exclusive i.e. only one of the 4 will be executed for each loop.

Chessboard

I really like how you’ve incorporated the flexibility to have an unequal number of rows and columns in your Chessboard :+1:

Just a couple of observations…

  1. The number of rows and columns output doesn’t correspond to the numbers input, because you need to either (i) assign 1 (instead of 0) to your iterator variables, or (ii) change the comparison operators in both for loop conditions from <= to <

  2. You can condense your conditional execution from 4 inner branches nested within 2 outer branches, into just one simple if...else as follows:
    (I’ve also added an additional space to your “white” squares as I think this improves the overall alignment of what is displayed on the page)

    if ((row + col) % 2 == 0) {
       toPrint = toPrint + "&nbsp ";   // additional space added to &nbsp
    }
    else {
       toPrint = toPrint + "#";
    }

Your conditional execution is fine… but it’s always good to condense IF our code still maintains its clarity, which I think, here, it does. But please feel free to disagree — these things are never 100% black and white… sorry, chessboard pun was unintentional :wink:

Hi Jon,
Thank you very much for responding to my work with constructive comments. I have fixed my Looping A Triangle code so that it has 7 rows, as the problem called for. I did leave out the document.write part as that was not called for in the problem. I do very much appreciate the tip though; it worked beautifully.

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

I want to thank you for going through my work in such a detailed manner.

1 Like

Hello @jon_m

thank you for you help! Unfortunately I recognized that some parts of my code (especially “br” and " ") disappeared by copy and pasting it in the forum. I’m not sure how to properly format the code, so everything can be read clearly.

Your tips are very much appreciated!
Thanks,
Alex

1 Like

Wow man, so good to read this, really a relief. Many times I thought I might be just not be clever enough to solve this sort of exercises. Thanks for the motivation :mechanical_arm: :mechanical_arm: :mechanical_arm:

2 Likes

Manage to solve the problem but with more logic than the solution :sweat_smile: :sweat_smile:

FizzBUzz

  <script type="text/javascript">
    for (var a = 1 ; a<=100 ; a++){
      if (a%3 == 0){
          if (a%5==0){
              console.log("FizzBuzz");
            }
            else{
              console.log("Fizz");
            }
      }
      else if (a%5==0) {
          console.log("Buzz");
        }
      else {
           console.log(a);
      }
    }

    </script>

Chessboard

    var matriks = 8;
    //var matriksb = 8;
    for (var a = 1; a <= matriks ; a++) {
      var toPrint =""
      for (var b = 1; b <= matriks ; b++){
        if (a%2==0) {
          if (b%2==0) {
            toPrint += "#"
            } else {
            toPrint += " "
            }
        } else {
          if (b%2==0) {
            toPrint += " "
            } else {
            toPrint += "#"
            }
        }
        }
      console.log(toPrint)
  }
1 Like

You’re very welcome!

I’m not sure I understand what you mean here. The code you posted displayed the output on the web page using  document.write(str);
All I was suggesting was increasing the amount of whitespace between the hashes, as I think then it looks more like a chessboard with alternate black and white squares. You correctly used "&nbsp"  to print whitespace, and you could make the space longer by just adding a space to the string:

"&nbsp "

Single keyed spaces are recognised in HTML, and displayed as whitespace, as long as they are not at the very beginning of the string. So this will give you a longer whitespace.

If you want to make the whitespace even longer, you would need to use another &nbsp, because only single keyed spaces are recognised:

"&nbsp &nbsp"     // I actually think this looks even better

"&nbsp  " 
// prints the same amount of whitespace as "&nbsp " (with just one keyed space)