Chapter 2 Exercises

you are amazing @jon_m. it never occurred to me to test odd shape grid. have made the necessary change. It turns out the double switch of characters is only required for even numbers so a simple conditional fixed the problem. It also gave me an opportunity to remove a few lines of code. there was no need to have the row and cols variables since myGrid has the value i need.

thanks for your feedback…

1 Like

Triangle

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

Fizz Buzz

for(var a=1; a<=100; a++){

    if(a%5==0 && a%3==0){
      console.log("Fizz Buzz");
    }
   else if(a%3==0){
      console.log("Fizz");
    }
      else if(a%5==0)
      {console.log("buzz")
           }
           else {console.log(a);}

Chess Board

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

Hi @cecilia!

Great coding! :+1:

All three of your solutions execute successfully, and solve the tasks, so don’t worry at this stage if they are less concise than the model answers. If you were new to JavaScript at the start of the course then you have done really well to come up with solutions that you have worked out for yourself. The model answers are something to aim for “in the end”. What would be a really beneficial thing to do now is to carefully work through the model answers, or other more concise alternatives posted and reviewed here in this discussion thread, and try to work out how they achieve the same result more efficiently. Try to see how you could make changes to your code to arrive at the more concise solutions, rather than just by starting again from scratch. It may not be possible, but your code is personal and meaningful to you, so it’s more motivating to at first try to work from where you got to.

Just one other point to mention…
Have a look at this post which explains how to format your code when posting it here in the forum.

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

Looping a Triangle:

for (let line = “#”; line.length < 8; line += “#”)
console.log(line);
// uses the for loop, line.length to let the program know to loop less than 8x.

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);
}
// " " is quotation marks around a space as a desired output. This exercises uses modulo, aka %, to calculate if a number has a remainder or not. If it does then it is equal to (==) 0. Also note the use of the || (or) logic operator to print the desired output.

Chess Board:

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);
/*for this you have to know that “\n” means a newline.
It’s actually a backslash: “\n”. It means a newline, like when you press the return or enter key. If you don’t include the \n, the next print statement will continue on the same line.
*/

1 Like

STACK STACK STACK STACK STACK🤑

SUCCESS! it's like, a a visual metaphor or something...and the process...teamwork makes the dreams work!

`for (row ="sats"; row.length <32; row += "sats"){ Console.log(row); }`

SHOUT OUT @jon_m for pointing me in the right direction. Ahhhh "" doesnt necessarily remake them as a single unit. Var not char 😆 details details details their everything

next up

Enter the Fizzzz

1 Like

triangle
for(n = 0; n<=7; n++){
hash = “#”;
for(c=0; c<n; c++){
hash += “#”
}
console.log(hash);
}

Fizz Buzz
for(number = 1; number < 101; number++){
dev3 = number % 3;
dev5 = number % 5;

if (dev3 ==0 && dev5 == 0) {
console.log(“FizzBuzz”) ;
}

else if(dev3 == 0){
console.log(“Fizz”);
}
else if(dev5 == 0){
console.log(“Buzz”);
}
else{
console.log(number);}
}

Chessboard

var grid = 8;
var hash ="";
for(let n=0; n<grid; n++){
for(let l=0; l<grid; l++){

if((l+n)%2==0){
  hash += " ";}
  else{
    hash += "#";}

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

1 Like
document.write("<strong>Looping a triangle</strong></p>"); 
let s, s1 = "";
for (let i = 1; i <= 7; i += 1) {
	s = ""
	for (let j = 1; j<=i; j += 1) {
		s += "#";
	};
	s += "<br>";
	s1 += s;
};
document.write(s1);

document.write("<strong>FizzBuzz</strong></p>"); 
for (var i = 1; i <= 100; i++){
  if (i % 5 == 0 && i % 3 == 0){ document.write("Fizz Buzz<br>");
  }
  else if ( i % 3 == 0 ){ document.write("Fizz<br>");
  }
  else if ( i % 5 == 0){ document.write("buzz<br>");
  }
  else { document.write(i + "<br>");
  }
};

document.write("<strong>Chessboard</strong></p>");
var size = 16, str ="";
for ( let n = 0; n < size; n++ ){
	for ( let m = 0; m < size; m++){
		if (( m + n ) % 2 == 0 ){ str += "&nbsp";
	  	}
  		else { str += "#";}
	}
str += "</br>"
}
document.write(str);
1 Like

Nice work, @Tordek :+1:
…and nice little finishing touch with the pop-up prompt for the board size parameter :ok_hand:

That’s fine, 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, and then when you look at the model answer, or another student’s solution, you first of all just “peek” at it, as you say, to get some hints; then if you really get stuck, by all means look at it in detail, analyse it, and kind of work backwards from there. You can learn a lot by working out what the solution does differently and how to go about “bridging the gap”. As long as you understand the code you’re finally posting, that’s job done! :slightly_smiling_face:

1 Like

Hi @Jody!

Well done for persevering, not rushing, and working things through at your own pace. These concepts take time to “click”, especially if you are new to programming.

You’re making good progress :ok_hand:

You’ve now cracked Fizzbuzz! :partying_face:

Looping a Triangle

You’ve now got a good base to work with… even if it is a bit long…I’m glad we don’t need to output 100 rows with your program! :wink:

So, lets take it in stages:

To cut down the for loops to just one, we need to do the following:

  • Change the condition in the first for loop to < 7
  • Move document.write("<br>"); to beneath document.write(hash); and within this first for loop.
  • Delete all the other for loops, so you’re just left with the first one.

Execute…
So, we’ve now got everything into just one for loop, the right number of rows (7), and the line breaks working. All we need to do now is print one additional hash on each consecutive row.

We need to somehow adjust our variable hash at the end of each loop so that when it’s referenced in the next loop, it has a value of +1#.

Can you work out what to add after document.write to achieve this? Try this yourself first, but if you can’t do it, then just let us know and we’ll tell you :slightly_smiling_face:

You can also merge the 2 document.write statements into just one using string concatenation.

I’m not just telling you the final code, as you will learn and understand so much more by working it out for yourself. The key is to break it all down into small logical steps, as I have above. As you progress, you can use this technique yourself whenever you get stuck.

.length evaluates to the number of characters in a string, so that’s why if we use .length in our for loop condition, we have to use a string as our iterator variable (counter) i.e. "#", instead of a number (numbers don’t have length properties).

var hash = "#";
console.log(hash.length);  // => 1

var hash = "#######";
console.log(hash.length);  // => 7

That’s why the solution that has the condition   hash.length <= 7   has an iterator variable of  var hash = "#";  , which also means we don’t need to declare this variable before our for loop like we do with the solution you’ve been working on.

The fog will gradually become a mist, and the mist will gradually clear :slightly_smiling_face:
Post your progress with Chessboard and any questions or difficulties you have, whenever you feel ready.

This is my problem now. I will start typing in atom or open a new file and the tags etc are not in colour and its producing nothing? how can I solve this ?

1 Like

Hi @matthurd,

You have to give the file a .html file extension. It’s untitled at the moment which is why it’s not highlighted. It doesn’t know what language/file type you want.

I normally do a Save As of a previous file of the same doc type i.e. in this case .html
In Atom:

  • Highlight file
  • File > Save As
  • Save file under different name but keep .html extension.
  • Delete everything you don’t want from previous file i.e. start from scratch if you don’t want to “cheat”, or keep certain tags/code etc. that you always use and don’t want to have to repeat again and again.
  • Triangle Loop
//ASSIGNMENT: Looping A Triangle

var pyramid = "7";
for (var row = 0; row <pyramid; row++){
  var Print = "#";

  for (var chain = 0; chain <row; chain++){
  Print += "#";
  }
  
console.log (Print);
}
  • FIZZBUZZ
//ASSIGNMENT: FIZZBUZZ

for( var digits = 0; digits <= 100; digits++ ){
  
  var change3 = ( digits % 3 == 0 );
  var change5 = ( digits % 5 == 0 );

  if( change3 && change5 ) console.log( "FIZZBUZZ" );
  else if( change3 ) console.log( "FIZZ" );
  else if( change5 ) console.log( "BUZZ" );
  
  else console.log( digits );
}

  • CHESS
//ASSIGNMENT: CHESS

var board = 8;
for (var row = 0; row <board; row++){
var pawns = (row % 2 == 0)? " ": " # ";
var Text = "";
for (var chain = 0; chain <board; chain++){

Text += pawns;
pawns = ( pawns == "#")? " ": "#";
}

console.log (Text);
}

@jon_m: Thanks for all the tips. Finally got this working in my :brain: :arrows_clockwise:

1 Like

Hi @Li_Sun,

Great attempt! :+1:

Your solution works for even-numbered sizes (e.g. 8x8) but not for odd-numbered sizes (e.g. 7x7). See if you can work out why and if you can modify your version to rectify this.

Hint:  you’re going to have to use individual square templates ("#" and " ") rather than your current double square ones (" #" and "# ").

Good luck! :muscle:

Jon,

Good Catch. No need to use individual squares, solution below. Now it works for both odd and even:

let white = ’ #’

let black = '# ’

let i = 1

let size = 11

while (i <= size) {

if(size % 2 === 0) {

    if(i % 2 === 0) console.log(black.repeat(size / 2));

    else console.log(white.repeat(size /2));

    i++

}



if(size & 2 !== 0) {

    if(i % 2 === 0) console.log(black.repeat(size / 2) + black[0]);

    else console.log(white.repeat(size /2) + white[0]);

    i++

}

}

1 Like

Hi @matthurd,

You’re nearly there with FizzBuzz:

…because you’re not telling it to…you need a final else statement that mops up all the numbers that aren’t divisible by 3 or 5 and logs them to the console as well. At the moment your conditional execution doesn’t handle them anywhere, and so effectively filters them out.

You also have another problem: You are logging x2 numbers divisible by both 3 AND 5. That’s because you have 2 if statements so you are handling this “FizzBuzz” category of numbers twice. You need to turn the second if statement into an else if and it’ll sort it.

I’m going to give you feedback on your Chessboard in a separate post.

Hi again, @matthurd,

Chessboard

This is actually the opposite problem to the one you had with FizzBuzz. Here you are telling it to print each incremental number in your iterator variable for each loop:

// Here you set your "counter" to 0 for the 1st loop
let i = 0;

// Here you increase your counter by +1 for each successive loop
i++

/* Here you are referencing the value of your counter variable i
  (i.e. the number) that it is holding for each successive loop and
  logging it to the console AS WELL AS YOUR STRING OF CHESSBOARD SQUARES */
console.log(i + "# # # # # # # #");
// Just remove the reference to i and you won't output the numbers.

Once you’ve sorted that, you’ll also have noticed that your “black” and “white” chessboard squares are aligned vertically, whereas they need to be offset (i.e. alternate positioning) on each row…as in…well, like a chessboard :wink:
So you need to find a way to further develop your program to include that functionality. If after having a good think you can’t do that, then take a look at the hints in the online version of the course book. They are hidden, and you can choose to display them by clicking on Display hints (in blue) below the exercise instructions.

Good luck! :muscle:

Hi @ashishc,

Good solutions :+1:

Your Looping a Triangle and Chessboard execute successfully, but unfortunately FizzBuzz doesn’t — and only because you’ve missed off the for loop’s final curly brace!

This could easily just be a copy and paste slip, but does highlight why it is so important to format your code when you post it here in the forum — something I’ve already explained to you in my feedback for your Chapter 3 exercises.

Hi @Long,

That’s really good that you’ve posted your own comments and reflections on the model solutions. It shows that you have thought about how they work :+1:

The idea is to post your solutions (or part solutions with questions), not the model ones from the course book — unless of course you came up with all 3 model solutions yourself before looking at them…? :wink:

Just a couple of observations…

No… this should be an empty string with no white space between the quotes. In fact, because of this your code doesn’t produce the correct output for FizzBuzz. Did you try to run it like this? Did you notice the problem and try to fix it? It’s important that you take those steps as it’s a really important part of the learning process.

You also have the same problem in your Chessboard code. Run it as it is now to identify what the problem is; see if you can find where the error is in your code; correct it, and then run your code again to check that you’re resolved the problem.

Yes :+1:

No… If the number does have a remainder then  num % divByisn’t equal to 0 because the number isn’t divisible by 3 and/or 5 and so the words aren’t logged.

Keep on learning! :slightly_smiling_face:

:raised_hands::smiley::raised_hands:

Yup… and unfortuntely that’s why the code you’ve posted throws an error…

console.log(row);   // LOWER case c

:upside_down_face::wink:

Great coding @hoolie :+1:

Please format all of your code (not just a bit of it :wink:) when posting it here in the forum. If you do that then:

  • It will be easier to read;
  • You can consistently apply nesting and identation;
  • It is easier for us to run your code and review it.

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