Chapter 2 Exercises

Great effort and i totally get what you mean. I am with you on practise practise practise. Keep going buddy and well done :facepunch:

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

// Looping Triangle
var hightOftriangle = 7;

for (var i = 0; i < hightOftriangle; i++) {

  var count = 0;
  var toprint = "";

  do {toprint += "#"; count++;
  } while (count<=i);
  console.log(toprint);
}

// Fizz Buzz (OR FizzBuzz)
for (var i = 1; i < 100; i++) {

   var printvalue = "";

   if ((i%3)==0)
     {printvalue = "Fizz";}

   if ((i%5)==0)
     {printvalue += "Buzz";}

   console.log(printvalue || i );
}

//looping Chessboard (resizable)
var size=8;
var pattern="";
var square=""

for (var hight = 0; hight < size; hight++) {
  for (var width = 0; width < size; width++) {

    if (((hight+width)%2)==0) {square=" ";} else{square="#"}
    pattern+=square;
   }
  pattern+="\n";

}
console.log(pattern);

The programs I created worked fine and did the job. After I had finished I looked at the hints and discovred the author’s approach was mind blowing!

1 Like


I don’t know why my atom doesn’t work on this.

Hi @CeesQ,

Sorry for the delay in giving you feedback on this.

These exercises are a real challenge, and so if you find one too difficult to solve on your own, or by doing some research, then that’s absolutely fine to end up looking at the model answer, as long as you have given it your best shot first. That’s the most important thing — to really spend time wrestling with it yourself first. You may just want to take a quick peek first to get some hints, so you can carry on and complete it yourself. The most important thing is how much you’ve learnt and stretched yourself in the process.

If you had to get some help, before moving on, make sure you spend time analysing how the model answers manage to achieve what they do. This is a really important stage in the learning process. You can learn a lot by working out what the solution does differently. Then you can apply what you’ve learnt next time, and keep improving.

That’s where this forum is an invaluable resource. Have a look at other students’ posts here in this discussion thread, with their attempts, solutions, and the help, comments and feedback posted as replies. There are a lot of comments and explanations posted here. You need to spend time browsing and reading, but you may well find that just one comment gives you the “Ah, ha!” moment you need.

Just one comment about your initial Chessboard solution…

I appreciate that this was just a “first step”, and that you are aware that it doesn’t fully solve the task; however, are you aware of its following limitations?

  • By dividing GridSize by 2 in the condition (to set the row limit), and by always printing 2 rows of hashes on each iteration, you cannot produce a board with an odd number of rows.

  • The number of columns cannot be modified, and will always be fixed at 8.

Again, it’s not so important that you found the solution with better functionality yourself, but that you understand how the model answer improves on what you were able to achieve.

Keep on learning! … You’re making great progress! :slightly_smiling_face:

1 Like

Hi @Changfa_Lin,

Some really good coding here! :+1:

Sorry for the delay in giving you some feedback.

Here are a few comments…

FizzBuzz

  • Your loop starts by handling the number 0. Did you intend to loop through from 0 to 100? If so, great! If not, then you need to adjust your iterator variable to start at 1 instead.

  • Using continue  (to exit the current loop and start the next one), isn’t actually necessary, because all of the statements in the loop’s body are mutually exclusive (i.e. only one of them will ever execute on each iteration, anyway). It’s better not to clutter our program with code that doesn’t add anything to what the code already achieves.

Chessboard

This is a great start — especially if this is what you managed to achieve on your own! :ok_hand:

You are probably already aware that the limitation with your solution is that it cannot produce boards with an odd number of columns (because it can only print pairs of “squares”: ' #' or '# '

If you haven’t already, make sure you spend time analysing how the model answer solves this. This is a really important stage in the learning process. It’s not so important that you found the solution with better functionality yourself, but that you understand how the model answer improves on what you were able to achieve. You can learn a lot by working out what the solution does differently. Then you can apply what you’ve learnt next time, and keep improving.

Keep on learning! … You’re making good progress! :muscle:

1 Like

This is a great start, @Kieran! :+1:

Sorry for the delay in reviewing it for you.

Sounds like your approach to these exercises is optimum, and you’re already noticing the results. Take your time, and go at a pace that feels right for you!

Keep on learning! :muscle:

2 Likes

Honestly, for a complete beginner I am really struggling here.

Triangle

var goal = "#"
while (goal.length<7){
console.log (goal);
goal = (goal + "#")
}
console.log (goal)

Fizzbuzz (Couldn’t figure out how to get the console to only print either the number, OR Fizz/Buzz/Fizzbuzz. It would always print both the number AND the word)

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

Chessboard - Don’t even know where to start for this one, couldn’t figure it out at all.

Feeling pretty frustrated, I’ve spent the last several hours trying to solve these and so far only figured out the first one. I’ve re-read Chapter 2 and still can’t figure out the solution to exercises 2 and 3 on my own.

What am I missing? I really want to understand how this works but especially the Chessboard exercise I am really not grasping.

Help/advice would be very much appreciated!

1 Like

Excellent coding, @BohemianJC :muscle:

This is such a great start! I can see that you’ve really thought carefully about these exercises. Your solutions execute successfully, solve the tasks, and each one shows a lot of originality in terms of the method you’ve adopted. :+1:

Your formatting is great too :star_struck:

Don’t panic! These exercises are a real challenge, and what you are experiencing is completely normal, especially if you started this course as a complete beginner. From what you’ve described in your comments, you’ve taken the right approach by spending a lot of time really wrestling with the task, thinking through the concepts, reviewing what you’ve learnt so far to see what you can apply, and then also doing your own further research. You’ll learn loads and progress quickly if you do these things.

When you finally look at the model answers (or other alternative solutions posted and reviewed here in the forum), notice whether they solve the task with code that is more concise than your version, or if they provide a superior solution with more functionality. If they do, then, before moving on, make sure you spend time analysing how the model answers manage to achieve what they do. This is a really important stage in the learning process. You can learn a lot by working out what the solution does differently. Then you can apply what you’ve learnt next time, and keep improving.

In terms of reflecting on how the model answer improves on your own solution, have a think about the following for your Chessboard:

In this statement, + "\n"  is actually redundant. The position of this console.log statement at the end of your outer for loop, means that it logs each row separately to the console. Each time the console.log function is called, its output is printed on a new line, anyway, and so we don’t need to add a line break character.

+ "\n" appears in the model solution, because the console.log statement appears at the very end of the program, outside of both loops. It logs the whole chessboard to the console in one go, as one single string: so, the line break characters need to be added to the string at the end of each row, in order to generate the right pattern.

Even though your code within the inner for loop is different to the model answer, you can still easily modify your version to log the whole chessboard to the console at the very end, rather than as separate rows, by making the following amendments:

var output = "";       // moved to the beginning, outside of the for loop 
var dimension = 8;
for (var row = 0; row < dimension; row ++) {
   // var output = "";  // moved to the beginning, outside of the for loop
   for (var column = 0; column < dimension; column ++) {
      ...   // no change to the inner for loop
   }
   output += "\n";  /* Individual rows are not logged to the console here,
                       but a line break character is added to a single string */
}  
/* the whole chessboard is logged to the console as a single string,
   at the very end of the program and outside of both loops. */
console.log(output); 

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

2 Likes

Excellent point! :joy:
Glad you found the feedback helpful though… even though I’m obviously living in a parallel chessboard reality… down a different rabbit hole! :upside_down_face:

2 Likes

Hi @FrankB,

Firstly, sorry for the delay in replying to you.

I’m glad that was helpful. I was going to say that they aren’t sequential else statements, but else if statements. However, on further reflection, I think what an else if sequence is actually doing is nesting a sequence of if...else statements, each one within the final else statement of its predecessor. Something like the following (note — this isn’t meant to be valid code, but just a visual representation):

IF… ELSE ( IF…ELSE ( IF… ELSE ) )

I actually have no knowledge of PASCAL, so I have forwarded this post to a colleague who will find the best person to answer this for you.

I’ve had a look at the history of this, and I’m very sorry you seem to have been left “hanging” in terms of a response regarding your later questions and Merkle trees. I have also passed this on to the same colleague who will again find the best person to provide you with the information you’ve asked for. I could probably look into it myself, but unfortunately I’m very pressed with this JavaScript course at the moment (hence my delay in replying to this very post :sweat_smile: )

Please rest assured I have made a note of who should be following this up for you, and I will make any necessary gentle reminders to make sure you get something tangible soon :slight_smile:

1 Like

Hey guys, my answers here. I figured out fizzbuzz but the chessboard not really but I managed to come up with something close that actually runs. This is my first time programming I have too many questions.
By the way I couldn’t run the script part on the console because I don’t know what the heck but what I did do is write it with the html and it works. Lol XD
FIZZBUZZ

Fizzbuzz
1 Like

Hi again, Frank,

About the switch statement, you mentioned:


I’ve had an experiment using a switch statement for this exercise, and this is what I’ve come up with, to give you an idea…
for (n = 1; n <= 100; n++) {
   switch (true) {
      case n % 3 == 0 && n % 5 == 0:
         console.log("FizzBuzz");
         break;
      case n % 3 == 0:
         console.log("Fizz");
         break;
      case n % 5 == 0:
         console.log("Buzz");
         break;
      default:
         console.log(n);
   }
}

Personally, I don’t like how we would have to state our expression (to be checked against our cases) as the Boolean value true. I think intuitively, the if...else statements provide a more appropriate fit to the logic we have here. But let me know if you think differently.

I’ve included a link above for you to read more about switch statements in the MDN web docs. However, generally speaking, I think that switch statements are more suitable when we want to check a list of items (represented by string values for example) to see if they match a given expression, and execute different statements or blocks of code accordingly. This expression lends itself nicely to serving as a variable input, and is therefore more likely to be coded as a variable, rather than as a fixed Boolean value true.

But anyway, the above code works and would therefore be a valid alternative solution :slight_smile:

1 Like

Hi @yestome,

Yes, these excercises are very challenging, especially if you started this course as a complete beginner.

Take a look at this post , where I’ve outlined my top tips for approaching any exercises you find too difficult to complete on your own. I think you’ll find it useful, and it should give you a few ideas for tackling them.

That in itself is a good result :+1:

Great achievement :+1:

This is where the techniques I discuss in the linked post should come in handy.

1 Like

Actually, the switch statement looks pretty good to me. It works the same way as in PASCAL except that PASCAL always looks a little nicer.

Thanks again, Jonathan—your answers are always very detailed, and I can see that you are really making an effort I very much appreciate your commitment…

1 Like

Hi @loksaha1310,

Great FizzBuzz solution :muscle:
… and nice formatting :ok_hand:

How are you getting on with Chessboard? Is it still work-in-progress? Let us know if you have any questions, or need help with anything :slightly_smiling_face:

Hi @Hamze_Dirir,

You’ve made a very good attempt at these exercises. There are some issues with your code (see below) but you’re very nearly there! :+1:

If you are new to programming, then applying the theory you’re learning to practical problem solving will take time to come more naturally, and so it will be a struggle at first. Also, these exercises are challenging, anyway.

So, what you’re experiencing is perfectly normal. You need to be patient and take your time. After you’ve done the exercises for the first time and checked and analysed the model answers, one learning technique I recommend is to 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 will help you to apply your theoretical knowledge quicker as the task is already familiar. It will get your brain working through the logical steps more quickly, which in turn will build up your confidence. It will also help with longer-term retention.

You need to format your code before posting it here in the forum. You can 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.
```
input your code here
```
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 (see below).

The code you’ve posted for FizzBuzz needs to be more spaced out, and you need to use indentation to clearly show the relationships between the different statements. At the moment it’s all squashed up together and this makes it hard to read. After formatting, and improving spacing, indentation and positioning of curly braces, your FizzBuzz should end up looking something like the code below. Apart from formatting, spacing, indentation and positioning of curly braces, the only other amendments I’ve made are:

  • Added opening and closing curly braces to enclose your for loop’s code block. Omitting these doesn’t prevent your code from executing, but they are an important part of making your code readable and “developer-friendly”.
  • For some reason you were trying to log a variable i (which doesn’t exist) in your final else statement. This prevented your code from executing and so I’ve changed it to num.
for (var num = 1; num <= 100; num++) {    // added for loop opening curly brace 
   if (num % 3 === 0 && num % 5 === 0) {
      console.log("fizzbuzz");
   }
   else if (num % 3 === 0) {
      console.log("fizz");
   }
   else if (num % 5 === 0) {
      console.log("buzz");
   }
   else {
      console.log(num);    // changed i to num
   }
}    // added for loop closing curly brace

Unfortunately your Looping a Triangle also fails to execute because you are logging the string "toPrint" to the console 7 times, rather than the variable toPrint. You should be picking up these mistakes (which we all make) by getting error messages when you test your code. If you format your code as I’ve explained above, this will also help you spot any mistakes like this one, which have crept in, before posting.

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

1 Like

Hi @linlin00,

Please post your actual code, and not screen shots. We need to be able to execute the code you are having problems with, in order to be able to debug it and find all types of errors.

You need to format your code before posting it here in the forum. You can 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.
```
input your code here
```
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. Have a look at some of the other students’ formatted code which they’ve posted here in this topic. This will give you an idea of what your formatted code should end up looking like.

When you post any code that you are having problems with, please also provide an explanation of what you are trying to achieve. From the screen shot you’ve posted it’s not clear whether this is your actual attempt at the exercise Looping a Triangle, or whether you’re just testing to see if your loop works by logging 1 to 7 in the console.

FIZZBUZZ

FIZZBUZZ

LOOP A TRIANGLE

Looping a triangle