# Chapter 2 Exercises

#124

My solutions were designed to output on both the webpage and console. Although the code may not be as sophisticated as some of the solutions posted here (or maybe even consider the required parameters, e.g., newline characters), the solution should be simple enough to follow.

Looping a Triangle

``````var asterisk = "#";

do
{
document.write(asterisk);
document.write("<br>");

console.log(asterisk);

asterisk += "#";
}
while(asterisk.length != 8);
``````

FizzBuzz Part 1

``````for(let counter = 1; counter <= 100; counter++)
{
if(counter%3 == 0)
{
document.write("Fizz");
document.write("<br>");

console.log("Fizz");
}

else if(counter%5 == 0 && counter%3 != 0)
{
document.write("Buzz");
document.write("<br>");

console.log("Buzz");
}
else
{
document.write(counter);
document.write("<br>");

console.log(counter);
}
}
``````

FizzBuzz Part 2

``````for(let counter = 1; counter <= 100; counter++)
{
if(counter%5 == 0 && counter%3 == 0)
{
document.write("FizzBuzz");
document.write("<br>");

console.log("FizzBuzz");
}
else if(counter%3 == 0)
{
document.write("Fizz");
document.write("<br>");

console.log("Fizz");
}

else if(counter%5 == 0)
{
document.write("Buzz");
document.write("<br>");

console.log("Buzz");
}
else
{
document.write(counter);
document.write("<br>");

console.log(counter);
}
}
``````

Chessboard

``````let line = "";

let size = Number(prompt("Enter a number for its squared size matrix:"));

for(let column = 0; column < size; column++)
{
if(column%2 == 0)
{
while(line.length < size)
{
document.write("&nbsp");
line += " ";

if(line.length < size)
{
document.write("#");
line += "#";
}
}
}

else //(column%2 != 0)
{
while(line.length < size)
{
document.write("#");
line += "#";

if(line.length < size)
{
document.write("&nbsp");
line += " ";
}
}
}

document.write("<br>");
console.log(line);
line = ""
}``````

#125

It was tough for me, too (well, still is, because I haven’t finished this exercise yet). Some of these ideas are weird to me, like incrementing a character string the same way you would a numeric value. (i.e., toPrint += “#”). That just seems strange. Or maybe that’s not what is going on. I’m still not sure and need to Google more.

#126

Thank you for giving the answer I was looking for on how to make these line breaks. All I was finding was “\r” (for carriage return) and “\n” (for new line) when I googled it, but those didn’t work for me. This “<br>” that you have DOES work however! Thank you!

#127

FizzBuzz

for(counter = 0; counter <= 100; counter++) {
if(counter % 5 == 0 && counter % 3 == 0) {
console.log(‘FizzBuzz’);
}
else if(counter % 3 == 0) {
console.log(‘Fizz’)
}
else if(counter % 5 == 0) {
console.log(‘Buzz’)
}
else
console.log(counter);

}

Chessboard

var size = 8;
var board = “”;
for (var row = 0; row < size; row++) {
for (var col = 0; col < size; col++) {
if ((row + col) % 2 == 0)
board += " ";
else
board += “#”;
}

}
console.log(board);

#128

hey bon,

here is a short explanation of what toPrint +="#" does. (maybe it help clarify things);

toPrint +="#" is a short version of toPrint = toPrint + “#”. What this does is it takes the toPrint initial value (a string) and appends to the end of that string the “#” character. You can understanding this operation as concatenating to the initial string a new string. ex: “bon” + “#” will result in “bon#”.
The “+” sign may be new to you, in terms of the concept of applying it to strings, but when you go deeper in to programming (C++ for eg.) you can see that you can program the operation that will happen when an operator (+, -, * …) is called and you can write code that is closest to the meaning and usage of that operator.

I hope this helped clarify this for you (and not deepen the confusion). If you need any help just ask.

See ya,
Mihai

#129

Thank you, that’s a great explanation!

#130

Hashtag triangle

var gridlets = “”;
for(i=1;i<8;i++){
gridlets+="#";
console.log(gridlets+"\n");
}

BUT, if I use document.write, I don’t get newlines. If I replace “\n” with “<br>”, it works fine.

Question 1) Why? (I think I used “\n” before, but I can’t get it to happen now.)
Question 2) Ivan’s example used nested loops. How do I determine which code executes faster?
Question 3) Similar to my #2, I know that for(i=1;i<=7,i++) will loop once less than for(i=1;i<8;i++), but the first expression has to run through evaluating “<=” seven times, while the second, though it has to do eight loops, only has to evaluate “<”. How do I find out which is more efficient?

#131

FizzBuzz

for(i=1;i<101;i++){
showMe=i;
if(i % 3 == 0) {showMe = “Fizz”}
if(i % 5 == 0) {showMe = “Buzz”}
if(i %15 == 0) {showMe = “Fizzbuzz”}
console.log(showMe);
}

#132

Chessboard

let size = Number(prompt(“Size?”));
let prnChr = “#”;
let prnStr = “”;
let thisChr = “”;

for(j=1;j<=size;j++){
if(prnChr=="#"){prnChr=" “;} // This if-else swaps blanks and gridlets
else {prnChr=”#";} // It could more elegantly be a function*
thisChr=prnChr; // But this probably uses less overhead

for(i=1;i<=size;i++){ // Having 2 temporary chars to work with
prnStr+=thisChr; // allows me to start each line with the
if(thisChr=="#"){thisChr=" “;} // alternate character.
else {thisChr=”#";}
}

prnStr=prnStr+="\n"; // Got tired. This is pretty kludgy. Gotta
// check out what others did.
}
console.log(prnStr); // But I DO like using the output only once.

``                            //* IS there an iif()?``

#133

Fizzbuzz script

for (i = 1; i<101; i++) {
if (i%3 === 0) {console.log(“fizz”);}
else if (i%5 === 0 && i%3 !== 0) {console.log(“buzz”);}
else {console.log(i);}
}

``````     for (j = 1; j<101; j++) {
if (j%3 === 0 && j%5 !== 0) {console.log("fizz");}
else if (j%5 === 0 && j%3 !== 0) {console.log("buzz");}
else if (j%3 === 0 && j%5 === 0) {console.log("fizzbuzz");}
else {console.log(j);}
}
``````

Chessboard script

var size = 8;
var row1 = " ";
var row2 = “#”;

``````     if (size < 2){
console.log("chessboard has fewer than 2 rows/columns. Make size >= 2");}
else{
// create 2 rows of length size - 1 row starts with " ", other with "1"
for(i = 2; i <= size; i++){
if(i%2 === 0) {row1 = row1 + "#"; row2=row2 + " ";}
else{row1 = row1 + " "; row2 = row2 + "#";}
}
// concatenate row1 and row2 and include line breaks
var allrows = row1 + "\n";
for(j=1; j < size; j++){
if(j%2 !== 0){allrows = allrows + row2 + "\n";}
else {allrows = allrows + row1 + "\n";}
}
console.log(allrows);
}``````

#134
1. Triangle

let number = "#";
while(number.length <=7){
console.log(number);
number = number + "#"; }

1. FizzBuzz

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

`````` if(numberr % 3 == 0 && numberr % 5 == 0){
console.log("FizzBuzz");
continue;
}
if(numberr % 3 == 0){
console.log("Fizz");
continue;
}
if(numberr % 5 == 0){
console.log("Buzz");
continue;
}
``````

console.log(numberr);
}

2. Chessboard

var size = 10;
var grid = “”;

for(var heigth = 0; heigth < size; heigth ++){
for(var width = 0; width < size; width ++){
if ((heigth + width) % 2 == 0){
grid += " ";
} else{
grid += “#”;
}
}
grid += “\n”;
}
console.log(grid);

#135

I wrote them for a web page

Triangle Loop:
var num_rows = 7;
for(var row = 0; row<num_rows; row++)
{document.write("#");
for(var column = 0; column<row; column++)
{document.write("#");}
document.write("
");}

FizzBuzz:
var total = 100;
for(var counter = 1; counter <= 100; counter++)
{if ((counter % 3)==0)
{document.write(“Fizz”);}
if ((counter % 5)==0)
{document.write(“Buzz”);}
if ((counter % 3)==0 || (counter % 5)==0)
{document.write("");}
else
{document.write(counter);
document.write("");}
}

ChessBoard:
var total_rows = 8;
var total_columns = 8;
for(var row = 0; row<total_rows; row++)
{if ((row % 2) == 0)
{for(var column = 0; column<total_columns; column++)
{if ((column % 2) != 0)
{document.write("#");}
if ((column % 2) == 0)
{document.write("

“);}
}
}
if ((row % 2) != 0)
{for(var column = 0; column<total_columns; column++)
{if ((column % 2) != 0)
{document.write(” “);}
if ((column % 2) == 0)
{document.write(”#");}
}
}
document.write("
");
}

#136

Chessboard:

var num_row = 25

for(row=0; row<num_row; row++) {
var toprint = " # # # # \n# # # #\n";

for (column = 0; column<row; column++)
toprint += " # # # #\n# # # #\n"; }

console.log(toprint)

#137

FIZZBUZZ

// 1. Print all numbers between 1 and 100
// 2. For numbers divisible by 3, print “Fizz”
// 3. Numbers divisible by 5 (and not 3), print “Buzz”
// 4. Numbers divisible by both 3 and 5 print “FizzBuzz”
let firstVar = 3;
let secondVar = 5;

for (l = 1;l<101;l++)
{
if
(l % secondVar === 0 && l % firstVar === 0){
console.log(“FizzBuzz”)
}
else if (l % firstVar === 0){
console.log(“Fizz”)
}
else if
(l % secondVar === 0 && l % firstVar != 0){
console.log(“Buzz”)
}
else {
console.log(l)
}

``````}
``````

===========================================

CHESSBOARD

// 1. Create Chess Board pattern 8 x 8.
// 2. User defines size of grid.

let grid_rows = 8;

// Simple pattern.
var toPrint1 = “# # # # “;
var toPrint2 = " # # # #”;
for (loop=1;loop < grid_rows/2;loop++) {
console.log(toPrint1)
console.log(toPrint2)
}
console.log(”------------------")

// User defined pattern.
let blackP = ["#"];
let whiteP = [" “];
let width_pattern=”";

var user_rowsW = prompt(“Please enter number of rows Wide required”);
var width_rows = parseInt(user_rowsW); // covert string into int
var user_rowsD = prompt(“Please enter number of rows Depth required”);
var depth_rows = parseInt(user_rowsD); // covert string into int

for (depth_row =1; depth_row <= depth_rows; depth_row++){
if (depth_row %2 === 0){
blackP = [" “];
whiteP = [”#"];
}
else {
blackP = ["#"];
whiteP = [" "];
}

``````for (width_row = 1; width_row <= width_rows; width_row ++){
if (width_row %2 === 0){
width_pattern += blackP.join();
}
else {
width_pattern += whiteP.join();
}
``````

}
console.log(width_pattern)
width_pattern="" // reset pattern ready for next row
}

#138

Hi @afs,

‘\n’ and ‘\r’ and invisible (control) characters which represent a ‘newline’ and ‘return’ respectively.
(The ‘\’ is reserved as a prefix for a control character, e.g. ‘\t’ for tab)

HTML does not render control characters; HTML only cares about markup tags (and their content), e.g.: <br/>, <p></p>, <h1></h1>, etc.

‘document.write()’ is a javascript command and amounts to: ‘write-some-html-in-the-document’:

`var someHtml = '<br/>';`
`document.write(someHtml);`

The following javascript will write a newline (control) character in the document but this is not rendered as HTML (if you view the source tho, you’ll see an extra empty line):

`document.write('\n');`

Conversely, outside the realm of markup (i.e. javascript and the console), ‘<br/>’ means nothing and will be treated literally.

`console.log('Literally: <br/>');`

output:
`Literally: <br/>`

whereas:
`console.log('\nAbove me is an invisible newline');`

output:

`Above me is an invisible newline`

#139

Can someone explain to me how I have from 2 to 8 instead of 1 to 7, thanks

Thanks

#141

@ivan we don’t really need 2 for loops for triangles

I printed results to html instead of console log for fun, there is some problems with spaces and break lines and html

## Looping a triangle

var num_rows = 7;
var toPrint = “”;

for (var i = 0; i < num_rows; i++)
{
toPrint += “#”;
document.write(toPrint + “
”);
}

## FizzBuzz

for (var i = 1; i <= 100; i++)
{
if(i%5 == 0 && i%3 == 0)
{
document.write(“FizzBuzz”);
}
else if (i%5 == 0)
{
document.write(“Buzz”);
}
else if (i%3 == 0)
{
document.write(“Fizz”);
}
else
{
document.write(i);
}
}

## Chessboard

var size = 8;

for (var i = 0; i < size; i++)
{
for (var j = 0; j < size; j++)
{
if((i+j)%2 == 0)
{
document.write("&nbsp&nbsp");
}
else
{
document.write("#");
}
}
document.write("
");
}

#142

#143

#144

FizzBuzz:

var fb;
for (i=1;i<=100;i++) {
fb = “”;
if (i%3==0) {
fb=“Fizz”;
}
if (i%5==0) {
fb+=“Buzz”;
}
if (fb!="") {
console.log(fb);
} else {
console.log(i);
}
}

Chessboard:

var height = (prompt(“Please give me the height”));
var width = (prompt(“Please give me the width”));
var board = “”;
for (j=1;j<=height;j++) {
for (i=1;i<=width;i++) {
if (j%2 == 1) {
if (i%2 == 1) {
board+=" “;
} else {board+=”#"}
} else {
if (i%2 == 1) {
board+="#";
} else {board+=" "}

}
}
board+="
";
}
document.write(board);