Chapter 2 Exercises

Hi @g00dstuff, Yes that is correct. I’m very happy that you found out these details by learning through the hard work. Keep up the good work! :muscle:

If the “pyramid” variable, when defined in the loop, will get reset after every loop. Just play around with the code as it is tough to convey it through text. You will figure it out :slight_smile:

Hi @Mroman, Can you please provide the code in the formatted code text so that we can test it out ourselves.

Happy Learning! :slight_smile:

2 Likes

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

Fizzbuzz

for (i = 1; 1<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 console.log(i);

}


ChessBoard

var size = 8
var board = “”

for (y = 0; y < size; y++){
for (x = 0; x < size; x++){

if ((x+y) % 2 ==0)
board += " ";

else
board += “#”;
}
board += “\n”;
}
console.log(board);

1 Like

Another observation:
I did spend 3 or 4 hours on exercises, solved them after several modifications, did it all in the browser console, then closed the browser by a mistake and didn’t save any work!!! All lost
Schould have done it in Atom as Ivan said and saved it!
Be careful!

      let z=1;
      let f="FIZZ";
      let b="BUZZ";
      for (x=1; z<=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(z)
      z++
      }

      let game = 8;
      let x = "# # # # ";
      let y = " # # # #";
      for (a=1; a<=game; a+=2){
      console.log (x + "\n");
      console.log (y + "\n");
      }

right now I’m having trouble in atom editor, displaying a browser preview. so when I’m entering code other than html, it’s not showing up in the preview window. It shows all the html, but not the java, there is no way to check my work to see if I understand the exercises. so Im kind of stuck here at this point until I can figure out how to resolve this issue. I like to know that what I’m entering is the desired result we are looking for for example the looping triangle, the Fizz Buzz and the Chessboard. without seeing that Im executing these correctly, I feel that cannot move forward from these exercises until I can resolve this issue. it sucks right now been researching youtube videos etc, if anyone can help with this it will be greatly appreciated. Ive got the HTML Preview download for Atom, The Live Server for Atom, and another one, in which all the html shows up but not the loops, in java.Ill keep working on it, until I have a preview window so I can se for myself that I programed The Looping Triangle exercise, The FIZZ BUZZ exercise and the Chessboard exercise. I need to know myself that I can program these.

so what I had to do is play around in the Code Sandbox ,Eloquent Javascript. It nice because you can enter some code and see the result it kicks back. Because of this wonderful tool, I was able to understand where my attempts at completing the exercises were falling short. so It was nice to see the actual code for each of the following, The Triangle Loop, FizzBuzz, and The Chessboard. I am having trouble with Atom being able to preview any of these exercises to my dismay. Im not sure if something is not linked up right in the program or what but I will eventually solve this so I can be more self sufficient in completing my exercises. I am however having a great time in this new world You sir, Ivan, have introduced me to and want nothing more. to fully understand and be able to develop my self within this awesome community! as always I feel blessed to be here, grateful and thankful!

These were very hard for me! Unfortunately, I needed to use multiple sources to find the answers as I was unable to complete the tasks on my own!

FizzBuzz:

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

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

“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