Chapter 2 Exercises

Nice coding, @AF90!

Don’t worry. That’s normal, and to be expected, as some of these exercises are a real challenge. As long as you have a go yourself and do as much as you can based on your own ideas first, then comparing what you’ve done with others is exactly what you should be doing, and is a great way to learn.

Before looking at other people’s solutions you can also have a look at the hints (which you can display in the online course book by clicking below the exercise instructions).

You can also look at the model answer given in the course book. Try to work out how it achieves the desired result, and then maybe think about how you would have done it, which could well be different. You should also use this technique when looking at other students’ solutions.

By the way, did you intend to program FizzBuzz to start at 0 and finish at 99 (instead of 1 to 100)? That’s fine if you did — we want to encourage innovation :wink: But if you meant to continue to 100, then have a think about the small amendment you can make to your code to fix this.

Keep up the great work! :muscle:

1 Like

Hey @JanjoHR1!

That’s great that you feel you’re now making good progress with JavaScript. You sound really motivated! :smiley: :muscle:

I’m also glad you’ve found the forum helpful for extra ideas and inspiration. You definitely seem to be using a good study method, by supplementing what you’re learning on the course with your own research on the Internet.

Your code is looking good :ok_hand:
I was particularly interested your very unique approach to Looping a Triangle :+1:

That’s fine because it sounds like you really gave it your best shot first. That’s the most important thing. To really spend time wrestling with it yourself first, and then when you look at the model answer, or another student’s solution, you kind of work backwards from there. As long as you understand the code you’re posting, that’s job done!

All your code runs perfectly :+1:

The only thing I would like to suggest for an improvement is your indentation, and positioning of the curly braces.

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. Your Looping a Triangle solution should end up looking something like this:

var a = 0, b = "#", c = b;

while (a < 7) {
   if (a === 0) console.log(c);
   else console.log(b += c);
   a++;
}

Where there is only a single statement in a code block, you can omit the curly braces.
If you use curly braces, the standard method, which is generally considered the clearest and easiest to read, would give you a loop as follows:

while (a < 7) {
   if (a === 0) {
      console.log(c);
   }
   else {
      console.log(b += c);
   }
   a++;
}

Keep on learning, you’re doing great! :muscle:

2 Likes

You’re very welcome Nancy!

The best advice I can give you is to move more slowly through the material. Experiment with it, make up your own mini programs, and make sure you run everything to check that it works. Working out where the bugs and errors are is also a very important part of the learning process.

If you found these Chapter 2 exercises very difficult, then to already be working on Chapter 4 after just a few days is too fast, in my opinion. The course is very intensive and covers a lot of concepts very quickly. So for someone who finds it difficult, I would definitely recommend supplementing it with additional material from the Internet, YouTube videos etc. That will help you to move through things more slowly and spend time consolidating before moving on. It’s all about building strong foundations.

Good luck, and enjoy the challenge! :smiley: :muscle:

2 Likes

i can find the answers on the internet… i am sorry on my one it will not work… i wil be taking the course from the beginning… i think i need a lot more exercise between the literature…

1 Like

Well noted, my mistake and thanks for advice, it really make sense.

1 Like

Thanks. I been working on this a few weeks now. I think I may go back to square one or pick up a different course and try again later.

Thank you

1 Like

It wasn’t a mistake. All I’ve done is suggested some improvements. Your original code is really good at this early stage in the course. Because I can see you’re really understanding stuff, I thought I’d just show you what to aim for next :muscle:

1 Like

These are the solutions:

EXERCISE 1

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

EXERCISE 2

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

EXERCISE 3

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

but guys, I tell the truth, I checked at the offered solution in the webpage. I got stuck 3 days on this matter, made some hundred of attempts, and there is always some kind of syntax error. I understand the basic points of the code, but I have no way to understand where are my mistakes.

Hello
I’m been doing the FizzBuzz exercise, but i get i bit stocked. I don’t know how to replace the number for Fuzz or Bizz in my code, if some one can help, I’ll be so happy

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

1 Like

Hi @cincinnato,

Firstly, well done for trying on your own for 3 days before looking at the solutions :muscle: You only learn by wrestling with the concepts yourself. However, the idea is not to get too frustrated. Before you look at the model solutions, try these approaches (probably in this order) first:

  1. Have a look at the hints (which you can display in the online course book by clicking below the exercise instructions).

  2. Do some research yourself on the Internet. There are even 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 watch a bit until they show you how to do the part you are stuck on. Then you could try to continue yourself… watch a bit more if you need to… etc. etc.

  3. Feel free to post your work-in-progress, or just a part of it, with a specific question about a particular problem you are encountering. This can be an effective approach if you would like help before you look at the solution. This is what @kmilo_Mart has done here.

  4. 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.

Once you have finally looked at the model answer given in the course book, you should attempt to work out how it achieves the desired result. From what you’ve said, it sounds like you’ve already done this. You could then do some more research about any code you don’t understand (Internet searches, browsing other students’ posts in the forum, or posting a question) and then try to write the code yourself without looking at the solution. You may well find that you do it differently but it still works. That’s fine as there are usually many different alternative approaches and solutions.

When you try to recreate the code yourself, if your code still isn’t executing after trying all the strategies I’ve described above, and you’re getting error messages which you can’t resolve yourself, then post them here and ask for more help.

These exercises are a real challenge, especially for anyone who was a complete beginner. It can take some time before you fully understand all the code in an exercise, so take your time, and another good strategy is to come back and revisit an exercise you didn’t fully understand after you’ve progressed a bit more through the course. You may well find that it’s much easier then.

I hope there is something in this post that you think will help you :slightly_smiling_face:

2 Likes

Hi @kmilo_Mart,

You’ve made an excellent start! :+1:

All you need is one more conditional statement (a 4th “branch”) which outputs “FizzBuzz” for numbers divisible by 3 AND 5. This needs to be the first branch, because it is the most selective: if you put it at the end, it wouldn’t do anything because the 1st statement would capture ALL the numbers divisible by 3 (those also divisible by 5 or not).

So, in this 1st conditional statement, you need a condition that requires both the Boolean expressions of the 2nd branch AND (hint) the 3rd branch to be true.

I would also use the keywords  if....else if.....else if....else  in that order for the conditional statements.

There is a more concise solution, but you really need to have understood how the logic of the solution I’ve described above works, before working on the “super-reduced” version :wink:

Good luck! :slightly_smiling_face:
Let us know if you have any more problems.

1 Like

LOOPING A TRIANGLE

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

FIZZBUZZ``

Re organizing the question to look for clues to translate to code
Write a program that uses console.log to print all the numbers from 1 to 100,
with two exceptions.
For numbers % 3==0 , print “Fizz” instead of the number,
For numbers % 5==0 (and not 3), print “Buzz” instead.

print “FizzBuzz” for numbers that are divisible by both 3 and 5
(and still print “Fizz” or “Buzz” for numbers divisible by only one of those).

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 scale = prompt("enter the size of the board");

var board = "";

for (var h =0; h <scale; h+=1){
  for (var w =0; w <scale; w+=1){
    if ((h + w) % 2 ==0) {
      board += " ";
    } else 
      (board += "#");
  } board += "\n";
}
console.log(board); 

These exercises took me about 24 painful hours to figure out. Feels like my brain is being rewired. Good luck to everyone.

1 Like

Good to know! I’ll stop getting stuck and I will be able to move on with the course. Thanks for the advice!

1 Like

Great coding, @RailGame!

Nice personal touches, and good formatting :ok_hand:

That’s the idea :muscle:

Only 24?.. you’re doing really well then! :smiley:

There are a few places where you can lose the parentheses. But I’ll leave that for you to work out for yourself as you progress through the course. It’s really only a minor point, and doesn’t affect the execution, but I’m just throwing it out there as something else for you to think about, in case the Chapter 3 Exercises only take you 6 hours :wink:

2 Likes

24 hours over the course of 2 days :laughing:
Thanks for the feedback. Its super challenging to remember the syntax while abstracting thought to come up with solutions. Like navigating a labyrinth but the walls are a construct of your own understanding.

1 Like
  1. Pyramid:

for (row = ‘#’; row.length <= 7; row += ‘#’)
console.log(row);

for (let num=1; num<=100; num++){
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”);
}
console.log(num);
}

  1. Board

var size = 8;
var board = " ";

for (var row = 1; row<=size; row++){
for (column =1; column<=size; column++){
if ((column+row)%2 ==1){
board = board + “#”;
}
else{
board = board + " ";
}
}
board = board + “\n”;
}
console.log(board);

1 Like

I really like this analogy!

1 Like

Hi @Lucky_Mkosana,

On the whole, very good! :+1:

Looping a Triangle :ok_hand:

FizzBuzz

When you run your code all the numbers are printed, as well as “Fizz”, “Buzz”, and “FizzBuzz”. This is because your final statement console.log(num) isn’t part of the conditional execution. To correct this all you need to do is just add else :

/* only prints the number when ALL of the conditions for Fizz,
   Buzz, and FizzBuzz evaluate to false */

else {                 
   console.log(num);                 
}

Chessboard

When you run your code, the first row is shifted one space too many to the right. This is only because your opening variable declaration   var board = " ";   adds an additional space right at the beginning. This can easily be corrected by removing this space as follows:

var board = "";

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 Chessboard should end up looking something like this:

var size = 8;
var board = "";

for (var row = 1; row <= size; row++) {
   for (var column = 1; column <= size; column++) {
      if ((column + row) % 2 == 1) {
         board = board + "#";
      }
      else{
         board = board + " ";
      }
   }
   board = board + "\n";
}

console.log(board);
2 Likes

Hello sir, could you please provide the exercises on this format? so we can review them?

Remember you can use the “Preformatted Text” Button to encapsulate any kind of code you want to show.


I am a happy Preformatted Text box, please use me wisely!

prefromatted_text-animated

Carlos Z.

2 Likes

Question:
When the Boolean if ((num % 3 == 0) && (num % 5 == 0) is true, output console.log(“FizzBuzz”); and nothing else till comes back to test it again ?

I’m doing my own simulation of by hand on paper to understand it better and this is what i figured out, well that is what I get from my result of the simulation on paper…

1 Like