Chapter 2 Exercises

chessboard

It works sir, just a little issue, each “chessboard” should be inside a “console.log” function to be able to showed in the console.

Like this:

let size = 8;
let chessboard = ""
for(row = 0; row < size; row++){
for (column = 0; column < size; column++){
if((column + row) % 2 === 0)
console.log(chessboard += "#");
else
console.log(chessboard += " ");
}
console.log(chessboard += "\n");
}

Hope this gives you a clear view of the subject, keep learning! :slight_smile:

If you have any doubt, please let us know so we can help you!

Carlos Z.

Hi all,

I found this exercise difficult. I spent many hours re reading the chapter, making attempts, and worked backwards from the answers until I could write the code without referencing. Here it is;

Triangle;
for (let a="#"; a.length<8; a+="#") console.log(a);

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

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

1 Like

LoopingTriangle

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

FizzBuzz

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

ChessBoard

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

1 Like

The Triangle Exercise:
var numSign = “#”;
var counter = 0;
var max = 7;
while(counter<max){
console.log(numSign)
counter++;
numSign=numSign+"#";
}

FizzBuzz Exercise:
var nums = 100;

    for(i=1; i<nums; i++){
      if(i%5==0 && i%3==0){
        console.log("FizzBuzz!")


      }

      else if (i%3==0) {
        console.log("Fizz")
      }

      else if (i%5==0) {
        console.log("Buzz")
      }
    }
    console.log(i)

The Chessboard Exercise:
var counter = 8;
var row=0;
var column = 0;

    var line="";

    for(var row = 0; row < counter; row++) {

    for (var column = 0;column < counter; column++){
      if((row + column) % 2==0){
        line+=" ";
      }
      else {
        line+="#";
      }
    }
  line+="\n";

}
    console.log(line);

These all work in the console tab of chrome.

1 Like

FizzBuzz

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

1 Like

Really well done for persevering! :muscle:

That’s a great technique to use. Another thing you can do here is post any of your own alternative pieces of code that either work, or you don’t know why they don’t work - there are usually alternative solutions. Also feel free to ask any questions about pieces of code used in the model answers that you struggled to understand.

A couple of comments:

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. You will see 2 sets of 3 back ticks.
```
```
If you now input your code between these, you will end up with nicely formatted code, which is then also easier for you to organise with the correct spacing and indentation etc. For your FizzBuzz you should end up with something like:

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

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. :slightly_smiling_face:

Also, notice I’ve added the keyword let to your variable definition. 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 (it doesn’t happen overnight) :wink:

Your code with Chessboard works, but be careful to use the right quotes: " and not 
I had to change them to get your code to run successfully.
Also, as with FizzBuzz, think about how you could improve the layout with spacing, indentation and nesting…

Keep at it, you’ll be progressing more than you realise! honest! :sweat_smile:

2 Likes

Just a comment:

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. You will see 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 indentation etc. For your Chessboard you should end up with something like:

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

Have a look at where I’ve added indentation and nesting in your code. The code still works without it, and some of the spacing is down to personal style, but it’s good practice as it makes the code easier to read and follow. :slightly_smiling_face:

2 Likes

Good stuff! :slightly_smiling_face: Have you had a go at Chessboard ? :wink:

Just a comment:

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. You will see 2 sets of 3 back ticks.
```
```
If you now input your code between these, you will end up with nicely formatted code, which is then also easier for you to organise with the correct spacing and indentation etc. For your FizzBuzz you should end up with something like:

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

Have a look at where I’ve added spacing, indentation and nesting in your code. It’s not mandatory, and some spaces are just down to personal style, but the indentation and nesting is considered good practice as it makes the code easier to read and follow. :slightly_smiling_face:
Let us know how you get on with the Chessboard challenge (or if you have any difficulties we can lend a hand with) :smiley:

1 Like
      //Triangle
      var numRows = 7;
      for (let row=0; row < numRows; ++row) {
        console.log("#".repeat(row + 1));
      }

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

      //ChessBoard
      let chessRows = 8;
      let oddRowString  = " #".repeat(4);
      let evenRowString = "# ".repeat(4);
      for (let rowNumber=0; rowNumber < chessRows; ++rowNumber) {
        let isOddRow = (rowNumber % 2) == 0;
        if (isOddRow) {
          console.log(oddRowString);
        } else {
          console.log(evenRowString);
        }
      }
1 Like

I can’t say I am good enough to do these on my own, but I did try several variations of these thanks to the forum. Here is my

FizzBuzz:

for (n = 1; n <=100; n++){
if (n % 3 == 0 && n % 5 == 0){
console.log(“FizzBuzz”);
continue;
}
if (n % 5 ==0){
console.log(“Buzz”);
continue;
}
console.log(n);
}

Chess:
let size = 8;
let board ="";
for (let x = 0; x <= size; x++){
for (let y = 0; y <= size; y++){
if ((y + x) % 2 == 0){
board += " ";
} else {
board += “#”;
}
board += “\n”;
}
console.log(board);
}

I got it to post the checkerboard, but it looks a bit funky.
Any tips would be appreciated!

1 Like

Thank you for the feedback Jon! It is very much appreciated and noted. :wink:

2 Likes

Thanks for the help jon_m.
I was wondering how I’m going to indent my code on the forum. Now I know! Tnx.
Yes, I got the chessboard right, but I didn’t use line breaks though, have a look:

var row_count = 1
var continue2 = true;
  while(continue2){
    row_count++;

  if(row_count%2==0){
    console.log(" # # # #");
}
  else{
    console.log("# # # # ");
  }
  if(row_count>8){
    continue2 = false;
  }
}
2 Likes

Chessboard

var row_count = 1
var continue2 = true;
  while(continue2){
    row_count++;

  if(row_count%2==0){
    console.log(" # # # #");
}
  else{
    console.log("# # # # ");
  }
  if(row_count>8){
    continue2 = false;
  }
}

Didn’t use line breaks though, but it worked! :grinning:

2 Likes

You’re very welcome!

Great attempt at the Chessboard ! :+1:

… and nice formatting :ok_hand:
Now think about how different statements nest within each other, and use the indentations for each further degree of nesting. This makes your program even clearer to other developers e.g.

var row_count = 1
var continue2 = true;

while(continue2){
   row_count++;

   if(row_count%2==0){
      console.log(" # # # #");
   }
   else{
      console.log("# # # # ");
   }

   if(row_count>8){
      continue2 = false;
   }
}   

Can you see that it’s now clearer at first glance, what is nested within what? First, we have our variables and our which statement. Within our which statement we have our if...else statements. Then within each if or else statement we have a third “level” of nesting.

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 console.log() statements; and
  • the row_count limit in the following if statement:
if(row_count>8){
   continue2 = false;
}

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 if statement above.

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. You will really learn loads by spending time at this “reflection stage”, and maybe trying to amend your version for this additional functionality. You may well find you can’t, and so you’ll learn a lot about how different approaches have different advantages and limitations, and their suitability in different situations (depending on what you want to achieve).

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

1 Like

Hey @AidanH

Great code for Looping A Triangle and Chessboard ! :smiley:

Have you tried running your FizzBuzz code? You’ll notice that it doesn’t output what we want…

1
2
Fizz
4
Buzz
Fizz
7…etc.

… but you only need to make a couple of minor changes to sort it. Rather than me telling you how to do it, I’ll give you a couple of hints — then you can have a go yourself, repost it and I’ll check it. If you’re still stuck, check out other student solutions here in the discussion and find one that adopts the same method/structure as you, and look at what they’ve done differently. If after that you’re still stuck, then of course let me know and I’ll provide you with the modifications… by spending time working it out for yourself, even if you succeed or not, you’ll learn loads in the process :smiley:

Hints

  1. You aren’t logging the numbers that aren’t divisible by 3 or 5 as you iterate through them. That’s because your final console.log() is after the for loop, and not within it.
  2. When you change that you will also need to adjust the comparison operator in the condition for your for loop, because otherwise you won’t reach 100.

Good luck! :muscle:

By the way, in your Chessboard code, you can also remove the row and column variables you’ve defined at the beginning because you define them anyway in the for statements. We want to make our code as concise as possible, because this makes it clearer, easier to understand, less bug-prone, and also easier to develop further.

1 Like

Great innovative and creative code @dAnijboned !.. some nice personal touches :smiley:

Nice use of the string method .repeat():+1:
You seem to really like it :wink:

Did you intend to only iterate up to 99 in FizzBuzz ? If not, then I’m sure you know how to make one tiny modification to take it up to the full 100 :wink:

By the way, think about how to also make a small modification to your Chessboard code so that it provides the functionality to adjust column number as well as row number, by only having to amend two variables which both store number values.

Keep up the great work! It’s a pleasure to read your code! :smiley:

1 Like

Hi, thanks for the hints. I think this is what your looking for.

  var nums = 100;

    for(i=1; i<=nums; i++){
      if(i%5==0 && i%3==0){
        console.log("FizzBuzz!")


      }

      else if (i%3==0) {
        console.log("Fizz")
      }

      else if (i%5==0) {
        console.log("Buzz")
      }
      else{
      console.log(i)
    }
  }
1 Like

That’s a great way to progress — you can learn loads by looking at other people’s solutions/attempts/variations and just experimenting with them :+1:

Don’t be too hard on yourself — these exercises are a real challenge! But that’s the idea :wink: You’ve actually done really well though. Here are some comments to help you on your way :smiley:

FizzBuzz

Interesting use of the continue statement (instead of else if and else statements) to manage the control flow in your for loop :ok_hand: Impressive stuff! :clap:
It’s probably just a copying error, but you also need to add a statement for just “Fizz” (when just divisible by 3) as well as for “Buzz”.

Funky Checkerboard

Yeh, you’ve definitely got a funky checkerboard going on here :wink: But with just a couple of extra tweaks, you’ll nail it! Rather than me telling you how to do it, I’ll give you a couple of hints — then you can have a go yourself, repost it and I’ll check it. But of course let me know if you just can’t see it, and I’ll provide you with the modifications… by spending even more time trying to work it out for yourself (with the hints), whether you succeed or not, you’ll learn loads in the process :smiley:

Hints

  • The main problem is the positioning of your last 2 curly braces
  • Then there’s an added twist of funkiness due to you coding for one too many iterations. If your board size is 8 x 8, then think about how to amend your for loop conditions to make sure they stop after 8 loops and not 9.

Good luck! :muscle:

2 Likes

FizzBuzz Exercise code
//Start by specifying how many rows we need.
var num_rows = 100;
for (var row=1; row <= num_rows; row++){
//This code will run as many times as specified above in num_rows.
if (row%3==0&&row%5==0){console.log(“fizzbuzz”);}
else if (row%3==0){console.log(“fizz”);}
else if (row%5==0){console.log(“buzz”);}
else {console.log(row);}
}

Chessboard Exercise code

var num_rows = 8;//Number of rows.
var toPrint = “”;//innitialized toPrint as blank.
var num_cols = 8;//Number of columns.
/* Did the for statement for the rows first because
we need to iterate inside the row./
for (var rows = 0; rows<num_rows; rows++){
/
The columns are just how many iterations until the end
of the row.*/
for (var cols=0; cols<num_cols;cols++){
if ((rows + cols)%2 == 0)
toPrint = toPrint+ “#”;
else
toPrint = toPrint +" ";}
/After the 8th iteration the newline will be initiated./
toPrint = toPrint+ “\n”;}
console.log(toPrint);

1 Like

Chessboard

var size = 8;

var board = “”;

for (var i = 0; i < size; i++) {
for (var j = 0; j < size; j++) {

if ((i + j) % 2 == 0)
board += " ";
else
board += “#”;
}
board += “\n”;
}

console.log(board);

1 Like