Chapter 2 Exercises

Hi @alex.k,

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.
```
input your code here
```
If you now input your code between these, you will end up with it nicely formatted, and you won’t lose the quotes or tags wrapped in angle brackets. Formatting your code also makes it easier for you to organise with the correct spacing and indentation etc. and to spot any errors or copy-and-paste slips.

Alright, thank you!!

1 Like

Sorry about that. I didn’t know there was an option to put the text properly…

Thank you for all the notes!

1 Like

I thought I was the only one struggling with this, the “FizzBuzz” exercise really threw me for a loop :slightly_smiling_face:
I’ve also had to go restudy this material many times, I think I’m getting a handle on it, but I need to look at it again and again, guess that’s how I learn. Cheers.

1 Like

Hi @Jaysun

Glad you’re finding some support here in the forum :muscle:

You’re not the only one, at all! 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.

I’m not sure how many of the posts in this topic you’ve already read, but here’s a summary of my top tips for approaching these exercises if you’re finding them difficult. I’d probably try them roughly in the following order (1-4 before you look at the solutions):

  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. For example, 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.

  5. When you finally look at the solutions, if they are different to your answers, you should spend some time analysing them. 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.
    But remember, there are usually many different alternative approaches and solutions to these exercises, so if you’ve coded yours differently, but it still works, then it may well be valid. If you’re not sure, then post it here, and we’ll review it for you.

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

  7. It can take some time before you fully understand all the code in an exercise, so take your time and don’t rush. 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.

Good luck! :muscle:

Hi @KingArt!

Well done for putting in the “heavy research” ! :muscle:

These exercises are a real challenge, so if you were a beginner when you started this course, heavy research is to be expected, and also what’s needed.

That’s a great idea. It’s a good learning technique to try the exercises again from scratch without looking back at the solutions (like a memory test). You can also try to do this after having left them 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.

It can take some time before you fully understand all the code in an exercise, so take your time and don’t rush. 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.

Just a couple of observations (which I’m sure are just unintentional slips):

// FizzBuzz - for loop condition
n<+100;      // loop exits after 99 (not 100)
// change to...
n <= 100;    // loop now exits after 100
// Chessboard - final console.log statement
console.log(board);  // throws an error because 'board' isn't a defined variable
// change to...
console.log(chessBoard);

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

  1. FizzBuzz
    for (var a = 1; a <= 100; a++){
    if (a % 15 == 0) {
    console.log (“FizzBuzz”);
    }
    else if (a % 3 == 0) {
    console.log (“Fizz”);
    }
    else if (a % 5 == 0){
    console.log (“Buzz”);
    }
    else {
    console.log(a);
    }
    }

  2. ChessBoard
    var board = “”;
    var evenRow = "# # # # “;
    var oddRow = " # # # #”;

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

    if ( i%2 == 0 ) board += evenRow + ‘\n’;
    else board += oddRow + ‘\n’;
    }
    console.log(board);

1 Like

Chapter 2 Exercises

  1. LOOP A TRIANGLE
for(row="#"; row.length<=7;row+="#")
console.log(row);
  1. FIZZBUZZ
for(let i = 1; i <= 100; i++){
let toPrint ="";
if(i % 3 == 0) toPrint += "Fizz";
if(i % 5 == 0) toPrint += "buzz";

console.log(toPrint || i);}
  1. CHEESBOARD
let size = 8;
		let board = "";
		for (let row = 0; row < size; row++) {
		   for (let col = 0; col < size; col++) {
			   if ((row + col) % 2 == 0) {
					board += " ";
				} else {
					board+= "#";
				}
			}
		   board += "\n";
		}
		console.log(board);`Preformatted text
1 Like
/*Fizzbuzz Assignment completed 14.06.2020
Rules as follows:
1. list numbers to 100
2. "fizz" for numbers divisible by 3
3. "buzz" for numbers divisble by 5
4. "fizzbuzz" for number divisible by 3 and 5

I managed to achieve this in a little under one hour with no help outside help.
*/
let f = "fizz";
let b = "buzz";
for(let num = 1; num<=100; num++){
  if (num % 3 == 0 && num % 5 != 0) {
  console.log(f);}
    else if (num % 5 == 0 && num % 3 != 0) {
    console.log(b);}
      else if (num % 3 == 0 && num % 5 == 0) {
      console.log(f+b);}
  else console.log(num);
}

/*CHESSBOARD Exercise 16.06.20
//Attempt No. 5697 (or something like that) :/ 
I tried a lot of different ways of writing this program.
I had it close so many times but couldn't seem to get it quite right,
sometimes it would show all iterations of both loop statements.
I kept getting stuck when attempting 'while loops' and getting caught in infinite loops
(my poor computer has been working very hard)
Also, I have not used any new line characters as requested in the exercise program.
After a few hours of getting stuck and trying different things,
I looked at the solution available in the Elequent JS Sand Box.
I could see how he had done it and it makes sense once I read it a few times,
but I mustered on with a different approach to see if I could spit out a program
that did what it was meant to in some way or another.  Proud that I stuck with it,
I obviously have a lot to learn though and I'm sure that someone will give me some pointers
as I'm aware that this is probably on elaborate way of writing the program and
a simpler solution is most likely right in front of my eyes.
*/
let size = 8;
let b = "#";
let h = " ";
for(let row = 0; row < size; row++) {
  if (row % 2 == 0){
    for(let cb = b+h; cb.length <= size; cb = cb + b + h){
      if(cb.length == size){
        console.log(cb)
      }
    }
  } else if (row % 2 !== 0){
    for(let cb = h+b; cb.length <= size; cb = cb + h + b){
      if(cb.length == size){
        console.log(cb)
      }
    }
  }
}

1 Like

Hey Jon,

Thanks for your email. That trick with the “&espn;” worked really well! Also thanks for the link, I had a quick browse and I think it might come in useful :slightly_smiling_face:

As for the console.log() dilemma. I’ll have a look at it again. Let’s see how this round goes.

Cheers
Em

1 Like

Could someone help please, I was not able to do it so I copied the solution from the book but the # are still not showing up. This is the code, could someone give me advice please! Thanks (Please be clear in your comment).

1 Like

OK, this wasn’t easy at all! I think I understood what was asked of me but I struggled to create it. For the buzzfizz I was maybe 80% correct but i had to keep looking online to try to find what i was missing. For example, I knew that I had to have %3=0 and that it had to print “buzz” but putting it in context for the console to read was not happening.
The last exercise was quite challenging. I kept printing 8# or 8#### but could not get the board out - I had to look it up :frowning:

2 Likes

OK, I’m going to start with statement that I’m super-new with all this, BUT, here’s my best shot… when I run what you wrote on my console I get the pyramid, alike the one in first exercise. I struggled with this as well, so what they had as a solution was to define the rows as 8 and grid to " “, then define the parameters:
for (let a=0; a<rows; a++){
for (let b=0; b<rows; b++){
and run if/else to basically state that if a+b are divisible by 2, print " " else print +=”#"
then they added grid +="\n"
then console.log(grid)…

so in case you’re stuck, this is what it looks like:
let rows = 8;
let grid = “”;
for (let y = 0; y < rows; y++){
for (let x = 0; x < rows; x++){
if((x + y) % 2 == 0){
grid +=" ";
}
else{
grid += “#”;
}
}
grid += “\n”;
}
console.log(grid);

1 Like

Here is my chessboard program (the indentations were lost in copying):

< html>
< script>
for(n=1; n<=8; n++){
let boardRow="";
for(m=1; m<=8; m++){
if((m+n)%2==0){
boardRow+="#";
}
else{
boardRow+=" ";
}
}
console.log(boardRow);
}
< /script>
< /html>

And here is my BuzzFizz program:

< html>
< script>
for(n=1; n<=100; n++){
if(n%3==0 && n%5!==0){
console.log(“fizz”);
}
else{
if(n%3!==0 && n%5==0){
console.log(“buzz”);
}
else{
if(n%3==0 && n%5==0){
console.log(“fizzbuzz”);
}
else{
console.log(n);
}
}
}
}
< /script>
< /html>

I tested them both and they worked properly…

1 Like

Dear @javedkhalil

Great work! Could you please tell me your thought process (logic) on your first solution?

The first part is very clearly, but the second one with the columns… I do not get the logic behind it. Could please help me with that :slight_smile: ?

1 Like

@ivan Is it possible to get videos on the solutions to see why it is coded that way? It is nearly impossible for me to understand the solution by just looking at the code. I need someone translating the thought process of the solution. Otherwise, it is just a waste of time to look at the answer…

Hi @natanieldp,

Nice solutions :ok_hand:

That’s absolutely fine! Your solutions execute successfully and solve the problems, which is the main thing at this stage.

What you should do, though, is spend time analysing how the model answers manage to achieve more concise solutions. 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 it does it. Then you can apply what you’ve learnt next time, and keep improving.

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

Hi @Anna,

Firstly, well done for producing solutions which execute successfully and solve the problems :ok_hand:

Please, 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.
To get an idea of what it should end up looking like, have a look at some of the formatted code other students have posted in this topic.


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 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 number of rows, and then replace the fixed 8 with this new variable’s name in the for loop condition.

However, 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.

Just one other comment…
Because you start your iteration at i = 0 your 1st row prints evenRow, your 2nd row prints oddRow etc. I’m sure this is the opposite to what you intended. You may want to think about how you can correct this as well.

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

1 Like

Hi @Mike_Power,

Please, 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.
To get an idea of what it should end up looking like, have a look at some of the formatted code other students have posted in this topic.

1 Like

Hi @cryptocrom!

Great coding, and great effort! :muscle:

From what you’ve explained in your notes, the approach you are taking with these exercises is optimum :+1:

These exercises are a real challenge, and if you find one really difficult, you should spend time wrestling with it yourself before looking at the solution (as you have done). If you’ve done that, then it’s absolutely fine to then take a look at the solution. You may just want to take a quick peek first to get some hints, so you can carry on and complete it yourself. In fact what you’ve done is even better: persevered with your own version! :muscle: It doesn’t matter if your final version is less concise than the solution. The most important thing is how much you’ve learnt and stretched yourself in the process.

However, if you needed to get help from the model answers, or if your alternative is less succinct, 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.

Your alternative Chessboard solution is very creative, and I enjoyed working out the logic you’d applied. The only comment I would make is that, unfortunately, it won’t handle any odd-numbered board dimensions (e.g. 7 x 7, or 9 x 9), only even-numbered ones (e.g. 8 x 8, 10 x 10 etc.). You may want to think about why that is, how you can modify your code to include that additional flexibility… or, as sometimes is the case, realise that this is a limitation to your method, so that you’ll know to take a different approach next time you need to code something with a similar kind of logic.

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

2 Likes