I think I understood this concept so far.
1000 thanks
I think I understood this concept so far.
1000 thanks
Hi @kmilo_Mart,
Exactly, because we only want each number to follow 1 of the 4 branches:
if
(multiple of 3 && 5)else if
(multiples of 3)else if
(multiples of 5)else
(i.e. none of the above)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â);
}
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.
looping triangle
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);
Thanks for your input, itâs so helpful!!!
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â;" ?
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);
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);
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 ?
Hi @Jody,
First of all, well done for getting this far with it
Now letâs see if we can put the finishing touches to it
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
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!
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
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!
Keep on learning!
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
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.row += "#"
< 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:
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++) {...}
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.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.document.write()
or console.log()
, but not both, because you want just one list either in the console or on the web page.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.
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.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) ? " " : "#";
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:
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?
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);
for(var char = "#"; char.length < 8; char += "#") {
console.log(char);
}
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);
}
}
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");
}
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.
<script language="JavaScript">
var triangleSymbol = "#"
for(rowCnt=0; rowCnt<7; rowCnt++) {
console.log(triangleSymbol)
triangleSymbol += "#"
}
</script>
<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>
<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>
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);
}
}