Chapter 2 Exercises

I think I understood this concept so far.

1000 thanks :+1:

1 Like

Hi @kmilo_Mart,

Exactly, because we only want each number to follow 1 of the 4 branches:

  1. if (multiple of 3 && 5)
     => if true, log “FizzBuzz”, then back to check loop condition for next number / if false, go to 2.
  2. else if (multiples of 3)
     => if true, log “Fizz”, then back to check loop condition for next number / if false, go to 3.
  3. else if (multiples of 5)
     => if true, log “Buzz”, then back to check loop condition for next number / if false, go to 4.
  4. else (i.e. none of the above)
     => log the actual number, then back to check loop condition for next number.
1 Like

Fizz Buzz

I don’t know how to replace the number with the word, I can only manage to print the word under the relevant number

for(counter = 0; counter<100; counter++){
console.log(counter);
if (counter % 3 ==0) console.log(“fizz”);
if (counter % 5 ==0) console.log(“buzz”);
if (counter % 3 && 5 ==0) console.log(“fizzbuzz”);
}

1 Like

Looping a triangle

**I first wrote the code to show on the webpage which used a hilarious amount of text… **
eg.
for(var counter = 0; counter<1; counter++){
document.write(hash);
}
document.write("
"); etc. etc.

When I tried to show it in the console it didn’t work… read some articles and have discovered I need to use .length

for (x = “#”;x.length<7;x+= “#”)
console.log(x);

**This was a challenge though… **

I tried to figure out the chess board but couldn’t do it. Had to look at the answer from the book.

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

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

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

Thanks for your input, it’s so helpful!!!

1 Like

My FizzBuzz solution:

for(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)
}

For the chessboard puzzle I have a question, what does this line do " board += “\n”;" ?

1 Like

LOOPING A TRIANGLE

var num_rows = 100;

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

var toPrint = “&”;

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

toPrint += “&”;

}

console.log(toPrint);

}

FIZZBUZZ LOOP

;

var counter = 1;

while (counter <= 100) {

if (counter % 3 == 0 && counter % 5 == 0) {

console.log(“FizzBuzz”);

} else if (counter % 3 == 0) {

console.log(“Fizz”);

} else if (counter % 5 == 0){

console.log(“Buzz”);

} else console.log(counter);

counter++;

}

CHESSBOARD LOOP

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:

  for(var i="#"; i.length<=7; i += "#"){
      console.log(i);
    }

FizzBuzz Loop

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

ChessBoard Loop

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

1 Like

Hello,

Thanks for all of your advises, I have one more Question:
I have no idea how to star the chessboard code, and I do not want to spoil myself looking at the others code, I want to think hard a bit but, Could you give me a hint ? :wink:

1 Like

Hi @Jody,

First of all, well done for getting this far with it :ok_hand:

Now let’s see if we can put the finishing touches to it :smiley:

One of the reasons this is happening is the location of your first console.log(counter);
For each loop (which prints for each number) you are always printing the number first, and then also performing your conditional execution to see if the number is a multiple of 3 and/or 5, and so also printing the words if it is.

You need to move this console.log and include it within the conditional execution, so that the number itself is only printed as a default i.e. if all the other conditions evaluate to false.

This should help you see the other problem that is at play here: you need to use a control flow of if…else if…else if…else statements, so that only one of the statements is executed for each number. At the moment it is executing all of the statements where the condition evaluates to true.

Amending for this will give you just one output for each number, but you will notice that there is still another problem — you aren’t printing any FizzBuzzes.
Part of the problem is here…

This will always evaluate to false, because you are saying: AND 5 must be equal to 0 :crazy_face:
The 2 conditions which must both be met are the ones you have already correctly written:

counter % 3 == 0
// AND
counter % 5 == 0

So you need to correct your Boolean expression so that both of these conditions are written in full either side of your AND logical operator. Arithmetic operators take precedence over comparison operators which take precedence over AND/OR operators, so the two separate conditions will be evaluated as either true or false before these true/false values are operated on by the AND operator. This means you don’t need any additional brackets, but you must code both conditions in full.

However, once you’ve corrected this, you still won’t get any FizzBuzzes. I’m not just going to tell you the solution, as it will be good for you to try to work it out for yourself and then repost here for us to confirm, but here is a hint: which condition/statement comes first is important…

Good luck! :muscle:

2 Likes

Hi again, @Jody!

Even if you can’t solve these exercises yourself, the most important thing is that when you look at the model answer in the book, or the many different other alternatives that have been posted and reviewed in this forum thread, that you spend time working out how and why the code solves the problem and outputs what it does. You don’t need to understand everything, but if there is lots of code in the solutions that you still don’t understand then you need to do some more research; and if you’re still struggling after that, ask about it here and we’ll help you out.
Have a look at the following posts where I’ve explained some good study approaches to take with exercises that you find you need help with:
https://forumtest.ivanontech.com/t/chapter-2-exercises/3078/680?u=jon_m
https://forumtest.ivanontech.com/t/chapter-2-exercises/3078/668?u=jon_m

Just be careful with the condition here. As our counter variable starts with the 1st character, instead of index [0] of an array, your code will stop at row 6 with ###### (# x6) whereas the exercise asks for 7 rows. You can easily add one more iteration by changing the comparison operator in your condition from < to <= as follows:

x.length <= 7;

There are other alternatives without using .length .  The following one is less concise, but you may find it easier to understand at first. It involves using 2 for loops, one nested within another. I think this might be the one Ivan uses in the video:

let numRows = 7;

for (let row = 0; row < numRows; row++) {
   let tr = "#";

   for (let col = 0; col < row; col++) {
      tr += "#";
   }

   console.log(tr);
}

Also, I’m not sure if you know, but 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. That will give you 2 sets of 3 back ticks…
```
```
If you now input your code between these, you will end up with it nicely formatted. You will probably still need to organise it a bit more with the correct spacing and indentation etc., but it’s much easier to do that effectively once it’s formatted than when it’s not. It also helps spot any errors, as the code is much clearer and easier to read. Your code should end up looking like my Looping a Triangle example above.

Yes :rofl:
If you want to use document.write() instead of console.log() you’ll need to add in an HTML line break element e.g.

for (let x = "#"; x.length <= 7; x += "#") {
   document.write(x + "<br>");
}

Try that, and the result shouldn’t be so scary! :wink:

Keep on learning! :muscle:

1 Like

Hi @Mucha_Julius,

Did you come up with your own solutions before you looked at the model answers? If the solutions you’ve posted are the ones you came up with first, then wow!..that’s great work, and a pretty amazing coincidence that they are exactly the same as the model ones :wink:

Hi @Omar,

Let’s see if we can give you a hand here…

Looping a Triangle

No…

  • let declares a variable which holds a string which serves as both (i) a “counter” (represented by the number of #s in the string) of the number of loops performed; and (ii) the actual row to be printed for the current loop.
  • The variable’s string (and with it the “counter” and the row length) is increased after every loop by the 3rd statement  row += "#"
  • After the “counter” has been increased, and before the next loop can start, the “counter” (or row length) is checked against the condition (2nd statement) to see if it is less than 8 #s (< 8). This effectively means that the last row to be printed by console.log(row)  is 7 #s, because when the “counter” increases to 8 #s, the condition fails and the loop is exited.

The clever thing about this solution is that the “counter” variable (row) is also the row to be printed during each loop.

FizzBuzz

You seem to have got a bit confused here. Here are a few pointers to help you have another go:

  • You don’t need two for loops, or the array stored in the var points variable. The only for loop you need should start in exactly the same way as your 1st for loop, except that it should start at 1 (not 0) and stop at 100 (not 99):
       for (var i = 1; i <= 100; i++) {...}
  • All of your conditional statements should now be included within the for loop, as you are going to log EITHER a number OR Fizz OR Buzz OR FizzBuzz for each loop. In other words you are dealing with each individual number from 1 to 100 during each individual loop.
  • So you do need a console.log() logging numbers, but not every number from 1 to 100. It needs to be included within the conditional execution, so that each number is only printed as a default i.e. if all the other conditions evaluate to false.
  • You also need to use a control flow of if…else if…else if…else statements, so that only one of the statements is executed for each number.
  • Your current Boolean expressions, if they evaluate to true, will display either Fizz or Buzz, respectively.
  • You need to either use document.write() or console.log(), but not both, because you want just one list either in the console or on the web page.
  • Your conditional execution needs a 4th branch (but not necessarily in 4th position (hint!) in order to display FizzBuzz for multiples of 3 AND 5. You need to combine both of the other Boolean expressions and operate on their resulting values with a logical AND operator.
  • And finally, as I’ve hinted at already… which condition/statement comes first is important…

Have a look at the following posts where I’ve explained some good study approaches to take with exercises that you find you need help with:
https://forumtest.ivanontech.com/t/chapter-2-exercises/3078/680?u=jon_m
https://forumtest.ivanontech.com/t/chapter-2-exercises/3078/668?u=jon_m

Chessboard

This is a great solution, but I can see that it’s one you’ve found and are trying to understand.

  • The outer for loop iterates through each row, and during each of its iterations the inner for loop iterates through each column i.e. building up each square in each row one by one.
  • When the inner for loop exits (at the end of each row) "\n" adds a line break, so that the next iteration of the outer for loop can start the new row on a new line. You can read more about this here.
  • board += (a % 2) == (i % 2) ? " " : "#";
    This line of code is a ternary operator and does the same thing as the following if...else statement:
if (a % 2 == i % 2) {
   board += " ";
} else {
   board += "#";
}

/* I actually think the ternary operator is easier to understand if it's
   written as follows: */
a % 2 == i % 2   ?   board += " "    :    board += "#";
// CONDITION     ?  if true do this  :  if false do this
/* the additional spacing either side of the ternary operator's symbols
   is just to make my comments clearer */

You can read more about the ternary operator in the MDN web docs:


Hopefully that makes things clearer. Just let us know if there is still anything you don’t understand, and don’t forget to post your updated FizzBuzz so we can check how you’ve got on :muscle:
1 Like

Hi,

I am struggling with the console. I am learning about loops and am inputting the code that the book uses as an example but it (the console) does nothing. This is what I am inputting:

let number = 0;
while (number <= 12) {
console.log(number);
number = number + 2;
}

Any ideas what I am doing wrong?

1 Like

i was really a problem, started the course from the beginning, but learned a lot of the exersice… i played a lot with the console, did research and yes… i will learn to program… but i had take a pause once and a while…

2
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 console.log(i);
}

3

var bord = "";
var evenRow = "# # # # ";
var oddRow = " # # # #";

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

    if ( i%2 == 0 ) board += evenRow + '\n';
    else bord += oddRow + '\n';
}

console.log(bord);
1 Like

Looping Triangle

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

FizzBuzz

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

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

Chessboard

      var boardNumber = 8;
      for(var row = 0; row < boardNumber; row++) {
        position = "";

        for(var column = 0; column < boardNumber; column++) {
          if((row + column) % 2 == 0) position += " ";
          else position += "#";
        }
        console.log(position + "\n");
      }
2 Likes
var hashtag = 1;
var hashOut = "#";

while (hashtag <= 7) {
	console.log( hashOut );
	hashOut += "#";
	hashtag++;
};
for (count=1;count<=100; count++){
	if (count%3==0&&count%5==0) {
		console.log("FizzBuzz")
	}
	else if ( count%3==0&&count%5!==0) {
		console.log ("Fizz");
	}
	else if ( count%5==0&&count%3!==0) {
		console.log("Buzz");
	}
	else {
	console.log(count);
	}
};
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);

I couldn’t figure out the chessboard pattern at all. I googled some examples online and I spent the past 3 days looking at the code constantly and thinking about it. I finally understand it today.

1 Like

Code to make triangle

<script language="JavaScript">
var triangleSymbol = "#"
for(rowCnt=0; rowCnt<7; rowCnt++) {
  console.log(triangleSymbol)
  triangleSymbol += "#"
}
</script>

Code for FIZZBUZZ

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

  }
</script>

Code for Chessboard

<script language="JavaScript">
let curChar = "#"
function switchChar() {
  if(curChar==="#"){
curChar=" ";
  } else {
curChar="#";
  }
}
let myGrid=prompt("What size do you want your grid");
  document.write("<table>");
  for(j=0; j<myGrid; j++) {
document.write("<tr>");
if(myGrid % 2 == 0) {
  switchChar();
} 
for(i=0; i<myGrid; i++) {
  document.write("<td>" + curChar + "</td>");
  switchChar();
}
document.write("</tr>");
  }
  document.write("</table>");
</script>
1 Like

Chapter two exercises
I am aware that my coding is longer and more complicated than the rest, but Im going based of what I’ve learned on chapter two only.

Looping a Triangle:

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

FizzBuzz Loop:

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

ChessBoard Loop:

var char1 = " ";
var char2 = “#”;
for (counter = 0; counter < 8; counter++) {
if (counter % 2 ==0) {
let string1 = char1;
for (let evenCounter = 0; evenCounter < 8; evenCounter++) {
if (evenCounter % 2 == 0) {
string1 = string1 + “#”;
} else {
string1 = string1 + " ";
}
} console.log(string1);
} else {
let string2 = char2;
for (let oddcounter = 1; oddcounter <8; oddcounter++) {
if (oddcounter % 2 == 0) {
string2 = string2 + “#”;
} else {
string2 = string2 + " ";
}
} console.log(string2);
}
}

1 Like