Chapter 2 Exercises

“Triangle Loop”

var rn =7
  for(var r=0; r<rn; r++){var tp = "#"
  for (var c =0; c<r; c++){tp +="#"}
  document.write(tp+"<br>")
}

“Fizzbuss Loop”

for (var m=1; m < 20; m++){
  if (m % 20 == 0) document.write("fizzbuss <br>");
  else if(m % 6 == 0) document.write("Fizz <br>");
  else if(m % 2 == 0) document.write("buzz <br>");
  else document.write(m + "<br>")
  }

“Double Chessboard Loop”

var size = 16;
  var area = " ";
  for (var row=0; row<size; row++){
    for(var column=0; column<size; column++){
    if((row+column) % 2==0) area += "&nbsp"
    else area += "#";
  }
    area+= "<br>";
  }
  document.write(area);
1 Like
	<script>
		// FizzBuzz

		for(var i = 1; i <=100; i++)
		{
			if(i % 3 == 0 && i % 5 != 0)
				console.log("Fizz");
			else if(i % 5 == 0 && i % 3 != 0)
				console.log("Buzz");
			else if(i % 3 == 0 && i % 5 == 0)
				console.log("FizzBuzz");
			else
				console.log(i);
		}
	</script>
	<script>
		//Chessboard

		var text = "";
		for(var i = 0; i < 8; i++)
		{
			for(var j = 0; j < 8; j++)
			{
				if((j + i) % 2 == 0)
					text += " ";
				else
					text += "#";
			}
			text += '\n';
		}
		console.log(text);
	</script>
1 Like
1.) Fizz Buzz


for (var i = 1; i <= 100; i++) {
	var message = "";
	if (i % 3 === 0) {
        message = "Fizz"
    } 
    if (i % 5 === 0) {
        message += "Buzz";
    } 
    console.log(message || i);
}


2.) Chessboard

let size = 8;

var board = "";

for (var y = 0; y < size; y++) {
  for (var x = 0; x < size; x++) {
    if ((x + y) % 2 == 0) {
      board += " ";
    } else {
      board += "#";
    }
  }
  board += "\n";
}

console.log(board);
1 Like

Triangle Loop

for (var row = "#"; row.length < 8; row += "#")
  console.log(row);

FizzBuzz

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

First I was going with this one but got stuck on returning the values where it’s neither Fizz or Buzz. And it would also duplicate the numbers divisible by both 3 and 5:

var printFizz = "Fizz"
var printBuzz = "Buzz"
var printFizzBuzz = "FizzBuzz"

for (let number = 1; number <= 100; number++){

  if (number % 3 == 0) {
    console.log(printFizz);
  }
    
  if (number % 5 == 0) {
    console.log(printBuzz);
  }
  if (number % 3 || 5) {
    console.log(printFizzBuzz)
  }
  else {
  console.log(number);
  }
}

Chessboard Loop

var size = 8;

var board = "";

for (var y = 0; y < size; y++) {
  for (var x = 0; x < size; x++) {
    if ((x + y) % 2 == 0) {
      board += " ";
    } else {
      board += "#";
    }
  }
  board += "\n";
}

console.log(board);
1 Like

I actually broke my head trying to understand how to solve those two and that got me really unstable

with FizzBuzz I ended up reviewing the answers of other students and after reviews I get it.

With Chessboard even reviews can’t help me… I’m stuck

So i wanted to take my time to really make sure i understand these exercises before posting my answers here, since the first answer was given to us by Ivan, and the third was so impossible for me to wrap my head around i actually had to look up the answer here in the forum, as well as looking up the Eloquent JavaScript solution. But now that i finally understand whats what, i think i’m ready to move on. (That and the fact that i already worked through chapter 3 as well as those exercises as well. Like, its long past time. :sweat_smile:)



  • Looping a triangle


So, for the first exercise, The Eloquent JavaScript solution is by far the most efficient way to solve this with the least amount of code. It simply uses a single for loop to generate the triangle, and by the textbook examples i had seen so far in the book, it's was also the most creative way I've seen the for loop be used. It immediately starts by defining a variable to be an empty string value, then uses the .length property of said string to keep track of the loops condition, and then increases the string value by a "#" for each iteration of the loop. The loop's code block contains one simple line of code, console.log(string) which makes sure that the loop generates the triangle in the console, one line at a time.

The code for this would be as follows:

 for (let string = "" ; string.length < 8 ; string += "#") {
     console.log(string);
 }


  • FizzBuzz


For the second exercise, FizzBuzz, i actually thought this exercise was so easy that i actually solved in the very first attempt as soon as i came upon it. I don’t mean to brag though, i’m sure this is child’s play to someone else reading this, but to me it was super exiting to just write some code and it works straight away. Anyway, since i learned about functions before writing this, i decided to embed my code into a function, just for fun.

function fizzbuzz(number) {
  for (let counter = 1 ; counter <= number ; counter++) {
    if (counter % 3 == 0 && counter % 5 == 0) {
      console.log("FizzBuzz");
      continue;
    }
    else if (counter % 3 == 0) {
      console.log("Fizz");
      continue;
    }
    else if (counter % 5 == 0) {
      console.log("Buzz");
      continue;
    }
    else {
      console.log(counter);
    }
  }
}

fizzbuzz(number);

Now i don’t know if i really need to explain what goes on here as it’s pretty straight forward.
I use the modulus/remainder operator (%) in an if / else if chain. In the first one it checks if the number held in counter is evenly divisible by both 3 and (&&) 5.

If it is converted to true, “FizzBuzz” is printed out and the keyword continue; alters the control flow so that the rest of the code doesn’t run and instead continues with the for -loop’s next iteration. If the first check isn’t converted to true, then it proceeds to the other two checks who tests if counter is evenly divisible with first 3, and then 5. (respectively)

If either check is true, it prints Fizz or Buzz (respectively). If neither of the checks converts to true, then it simply prints out the number held by counter. And lastly, since i made it into a function. You can simply call it by writing fizzbuzz(number), where number is the parameter where you pass your argument of how high you want the function to test. This way you could insert any number (unless it’s so high and your machine runs out of memory and crashes). So basically, this function is a way to test which numbers are evenly divisible with 3, 5, or both. From 1 all the way to a number of your choosing.



  • Chessboard :skull_and_crossbones:


Aight so this exercise kinda made me wish i had hair just so i could pull it out.
I had to look it up eventually, even though i really don’t like “cheating” in these exercises, i felt like there was no way i could figure it out on my own. But i guess the point if these exercises isn’t prestige or pride but actually understanding them. I think i do now though.

Also, since a point in this exercise is scalability, i decided to also make it a function.
So here is my code before i go on to explain it:



function chessboard(size) {
  let string = ""
  for (let height = 0 ; height < size ; height++) {
    for (let width = 0 ; width < size ; width++) {
      if ((width + height) % 2 == 0) {
        string += " "
      } else {
        string += "#"
      }
    }
    string += "\n"
}
console.log(string);
}

chessboard(8)

So, for the sake of scalability and user-friendliness i made it into a function that you simply call by typing chessboard(size); where size is the parameter where you pass your argument for how big you want the chessboard to be.
So chessboard(8); for example, generates an 8x8 grid.
What the function body does first is that it defines the variable string to simply be an empty string value. It is then followed by a loop containing yet another loop. The variables in the textbook examples are originally named x and y but i thought it would be easier to name them height and width, the reason that we use two loops like this is because the function works two angles.

The first for loop keeps track of the number of lines by starting with 0, and incrementing by 1 for each iteration of the loop, as long as it is less than the parameter size
(that you pass your numeric argument into when you first call the function).

Now, since the first loop’s body contains yet another loop, after the first iteration of the outer loop, control goes into the inner loop. This loop handles the width of the chessboard, or rather, the characters on each line.

It does this just like the first loop, it starts from 0, incrementing by one while its value is less than the size (that you gave it) - however, after each iteration of its loop, it proceeds to the code block contained within it - and this is where the magic happens.

The if statement that follows compares the sum of the values contained in height and width, and uses the modulus operator (%) to determine if the remainder of this sum is 0 when divided by 2.

  1. If this is converted to true, the empty string value contained in the variable string gets updated (concatenated) with a blank space " ",

  2. If the statement is converted to false (the sum of height and width isn’t evenly divisible by 2, = the sum is an odd number), the variable string instead gets updated (concatenated) with a hashtag “#”.

Once the code inside the inner loop has run its first time, the loop yet again increments its value width with one, and once again runs the if statement. This is the code that decides whether a blank space, or a hashtag should be concatenated next to the once-empty string in the beginning of the function body. The way control flow works makes sure that the inner loop runs all the way up until it has generated one entire line of the chessboard (until the width variable is no longer < size), before control proceeds out of the loop.

However, there is one last stop before control comes back to the outer loop. The cleverly added newline character (\n), or rather, the concatenation of a newline character into the very same string that the inner loop was just working on. This, together with the first (outer) loop is what makes sure that the chessboard string that is later printed out at the very end of the function is nicely and evenly cut up into size-number of times.

When control flow once again comes back to the first for-statement to iterate its second loop, the height variable is incremented by one, so when the inner function, with the help of its if-statement, then starts to cycle through width and test which character to add next chessboard string - It does the exact same thing again, except producing the “opposite result” each time. The first iteration started with an even sum (height + width). The second time however, since height is increased by one, the second iteration now starts with an odd sum.
This is what makes it so that the chessboard alternates the layout of the hashtags and spaces.

The function does this over and over, generating line after line, separated with a newline character. And only once both loops have run until their respective courses and no longer meets the condition (variable < size). The program finally prints out the now fully generated single string, consisting of hashtags, spaces and newline characters, representing a chessboard.

Sorry for wall of text. I guess i understand it now though. :innocent:

5 Likes

Triangle

for(var row = 0; row < 7; row++){
var text = “#”;

for(var column = 0; column<row; column++){
  text += "#";

}

document.write(text+"
");
console.log(text);
}

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

else console.log(i);

}

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

1 Like

@max_wolflife
good solution, but in the frist one, you do not have to use two variables(x and z ). one(x) would be enough. you can use only x to check if the condition in the loop. could you improve it ? :slight_smile:

1 Like

@grhpurchase
did you try to run your frist solution(fizzbuzz) ? you will get an infinite loop. could you find you bug and fix it ? :slight_smile:

2 Likes

@GalacticBrainBomb9 could you post a screenshot?

1 Like

Greetings @Palmeguppsi,
An extremely well thought out and a well articulated answer. I wish I could give you multiple hearts for this answer. Well done. Keep up the same momentum. :smiley: :muscle:

Infact, I’ll refer your answer to other student’s questions on the chessboard exercise.

Happy Learning! :slight_smile:

1 Like

Hi @OhD.Crypto, Could you go through this answer and check out the chessboard answer. Chapter 2 Exercises

It is well documented. Please reach out if you have any doubts.

Happy Learning! :slight_smile:

2 Likes

Hello @Malik,
Thank you for those words! I’d give you multiple hearts for this reply as well! :smile:

I am very honored by this. Thank you again sir! :pray:

1 Like

Triangle Loop Exercise

for (var line = "#"; line.length < 8; line += "#")
        console.log(line);

Chessboard Exercise


let chessBr = " # # # #"
let chessBl = "# # # #"
for (let i = 0; i < 4; i++) {
  console.log(chessBr)
  console.log(chessBl)
  }

FizzBuzz Exercise

for (let number = 1; number <= 100; number++) {

  if (number % 3 == 0 && number % 5 != 0)
    console.log("Fizz")

  else if (number % 5 == 0 && number % 3 != 0)
    console.log("Buzz")

  else if (number % 3 == 0 && number % 5 == 0)
      console.log("FizzBuzz")
  else {
        console.log(number)

     }

}
1 Like

Headache!! Managed to do FizzBuzz quickly, for some reason, I just knew what I needed to do on that one… Chessboard was a different matter. After a couple of days, I gave in and looked at Google and the Forum… finally after starting again with a clear head, the penny dropped on the logic and I flushed out the use of a comma not a semi colon!

Here’s the code:

// LOOPING A TRIANGLE TASK

  var row_num = 7;
    for (var row = 0; row < row_num; row++){
      var toPrint = "#";
      for(var column = 0; column<row; column++){
        toPrint += "#";
    }
    console.log(toPrint);
  }

// FIZZBUZZ TASK

      var number = 0;
      while (number <=100) {
        // if the number is divisible by 3 and 5 show BuzzFizz
        if ((number % 3==0) && (number % 5==0)) {
          console.log("FizzBuzz")}
        // if the number is divisble by 3 show Fizz
        else if ((number % 3==0)) {
          console.log("Fizz")}
        // if the number is divisible by 5 show Buzz
        else if ((number % 5==0)) {
          console.log("Buzz")}
        else {
          console.log(number)}
        number++;
      }

// CHESSBOARD TASK

var size = 8; //this is the value that can change to make the chessboard a different size
var string = ""; //string we are building, will add " ",# or new line to it

for (var row = 0; row < size; row++) {   /*outer loop - we add new line to seperate the rows*/
  for (var col = 0; col < size; col++) { /*inner loop - it adds a " " or a # to the line*/
    if ((col + row) % 2 == 0)  /*col from inner loop, row from outer loop. col will = size before row increases*/
      string += " ";  // even so " " is added
    else
      string += "#";  // odd so # is added
  }
  string += "\n"; //outer loop added the new line
}
console.log(string); //last action, shows the completed string
1 Like

ERXERCIES 2 CHESSBOARD

Hi together, I posted this code a few days ago on the
" I am stuck " section in the forum and thecil advised
me to post a replay here.Capture d’écran 2020-08-16 à 16.42.17
‹4

I made some changes on my code , but I didn’t have the expected result.

Instead it gave this
Capture d’écran 2020-08-16 à 16.34.33

So well… I am stuck and I need some helpful advice.

Thanks in advance for your help and advices.

    https://forum.ivanontech.com/t/chapter-2-exercises/3078/1074?u=max_wolflife

      let f="FIZZ";
      let b="BUZZ";
      for (x=0; x<=100; x++){
      if (x % 3 == 0 && x % 5 == 0) console.log (f+b);
      else if(x % 3 == 0) console.log(f);
      else if(x % 5 == 0) console.log(b);
      else console.log(x)
      x++
      }
1 Like

… I cant do it. Ivans example doesn’t even do anything on my Website for some reason, Clearly ive done something wrong…

Absolutely stuck and ready for throwing the laptop off the wall. :rage:

I forgot a semi-colon to stop the loop and my computer crashed LOL. Lesson learned - details are vital!!

1 Like

Hi @Amri2020, Hope you’re having a wonderful day.
Well, while going through your code, I could find out some issues in the syntax.

First, the if statement brackets are wrongly placed. The console.log("#") should come after the bracket starts.

Second, I see the line
for(let squareLine=0; squareLine<=8; "\n");
Here the third argument in the for statement is a "\n" which is incorrect. If you do not manipulate the “squareLine” to the next number, it will never reach the condition of squareLine<=8, this will result in an infinite loop and thereby crashing your compiler.

Third the syntax let= "\n" is also incorrect, you need to give the variable name first for a let statement. For example - let line = "\n";

Lastly, keeping aside the syntax, the logic of flow is incorrect as well. I suggest you go through this post for clarity. It is well documented.


Or you could check out the animation that I provided for better understanding in the below post.

Hope this helps.

Happy Learning! :slight_smile:

1 Like