Chapter 2 Exercises

Exercises – Chapter 2 in the book EloquentJavaScript

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

}

2. 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++;

}

3. 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);

I started doing the exercises before watching Ivan’s video, so here is my code:

  1. Triangle
    let triang = “#”

    while (triang.length < 8) {
    console.log (triang); triang = triang + “#”
    }

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

It took me quite some time to get this result

  1. Chessboard
    I spend hours doing this exercise, but since I had not watched the explanation video, I wasn’t exposed to the row and column idea, so after coming to the conclusion that I didn’t know how to do it, I checked the answers… not proud.

    let size = Number(prompt(“Pick the size of the board”))
    let board = “”;
    for (var row = 0; row < size; row++) {
    for (var column = 0; column < size; column++) {
    if ((row+column)%2 ==0) {
    board += " "
    } else {
    board += “#”
    }
    }
    board +="\n"
    }
    console.log(board)

var one = " # # # #";
      var two = "# # # # ";
      var num_rows = 8;
      for(var row = 0; row <= num_rows; row++){
        if(row % 2 == 0){
          console.log(two);
        }
        if(row % 1 == 0){
          console.log(one);
        }
        console.log(row);
      }

How do I rid of the numbers when it is executed? Also, I am trying to find out different ways of doing this without copying other people.

Tiangle loop
Why is everyone using 2 for loops? I wrote this and it worked:

let hash="#";
for (let i=0; i<7; i+=1 ){
console.log(hash);
hash=hash + “#”;
}

Personally, I wrote mine with two for loops to be explicit about the fact that the solution was building rows of hashes. It was a decision toward readability, but there are many ways to write a program. In production code it is better to be explicit in what your programs are doing, because when you come back to it you may have forgotten how it accomplishes its tasks not to mention if someone else ends up with with code and needs to modify it for some reason.

I don’t know about anyone else but I had to have help. When I read the forums I could see that some others did too because of the way some of the code is written. I found many different ways to solve problems. What I discovered is that even experienced coders have to work through the problems step by step. I also learned the attention to detail. I also learned to make an outline of what it takes to write the code that solves the problem and then to tackle the problem step by step checking the outcome as I go.

I did enter the code along with the experienced coder who was solving the riddles. I recalled reading in the text book that “The art of programming is the skill of controlling complexity. The great program is subdued—made simple in its complexity.” So, I tried to look for the simplest and “cleanest” code.

Finally, the attention to detail was paramount. Often my code did not produce the same result as the experienced coder. In my code for the Chessboard I was unable to get the same result as the code I was following. Everything looked the same but the console.log was not producing the correct result. After comparing code for an hour or more the simple parenthesis in the "var board = “” had to be side by side for no assigned value and not separated for a blank value. The error was so small that it was easy to miss. So, I learned a lot about coding from this exercise.

I’m a senior citizen but I can still think and I am enjoying the challenge of coding.

3 Likes

Good stuff Paul, you’ve nailed the essence of the situation and garnered insight through experience. Best way to progress :smiley:

2 Likes

1.Looping Triangle
let ToWrite = “#”;
for (i = 0; i < 7; i++) {
document.write(ToWrite + “
”);
ToWrite += “#”;
}

2.FizzBuzz
for (i = 1; i < 101; i++) {
if ((i % 5 == 0) && (i % 3 == 0))
console.log(“FizzBuzz<br>”);
else if ((i % 5 == 0) && (i % 3 !== 0))
console.log(“Buzz<br>”);
else if (i % 3 == 0)
console.log(“Fizz<br>”);
else
console.log(i + “<br>”);
}

3.Chessboard
let size = 1, board = “”;
while ((size % 2 !== 0 ) || (size < 2)) {
size = Number(prompt(“Give an even number please”));
}
for (i = 1; i <= size; i++) {
for (j = 1; j <= size; j++) {
if ((j+i) % 2 == 0)
board += " ";
else
board += “#”;
}
board += “\n”;
}
console.log(board);

let toprint=""
for(i=0;i<7;i++){
toprint+="#"
console.log(toprint)
};

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

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

let size = 8;
for(i=0;i<size;i++){
let a=""
if (i % 2 == 0)
do {
a+=" #"
}
while (a.length<size);
else do {
a+="# "
}
while (a.length<size);
console.log(a);
}

Ex#1
for(var row=0; row<7; row++){
var hashtag="#"
for(var num_hashtagtoadd=0; num_hashtagtoadd<row; num_hashtagtoadd++){
hashtag+="#"
}
console.log(hashtag)
};

Ex#2
for(var count=0; count<100; count++){
if((count+1)%3==0){
if((count+1)%5==0){
console.log(“FizzBuzz”)
}
else{console.log(“Fizz”)}
}
if((count+1)%5==0){
if((count+1)%3==0){
console.log(“FizzBuzz”)
}
else{console.log(“Buzz”)}
}
else{console.log(count+1)}
};

Ex#3
for(var count=0; count<8; count++){
if(count%2==0){
var x=""
for(var a=0; a<4; a++){
x=x+" #"
}
console.log(x);’/n’;
}
else{
var y=""
for(var b=0; b<4; b++){
y=y+"# "
}
console.log(y);’/n’;
}
};

//FizzBuzz exercise
for (let a=1; a<101;a++){

if(a % 3 ==0 && a % 5 ==0){
console.log(“FizzBuzz”); continue;
}
if (a % 3==0) {
console.log(“Fizz”); continue;
}
if (a % 5==0) {
console.log(“buzz”); continue;
}

console.log(a);
}

TRIANGLE
/*
If you make your variable “i” a symbol instead of a number, it will display
those numbers.
The length of i has to be less than eight because it wil display 9
if you put less than or equal to because the computer starts at 0.
The amount of # will be displayed by line but will stop displaying
before 8 and can only display up to 8 lines and 8 #'s because of
the compounding of +=. It will add a # to each line, coming from the previous
line to display 1 more for each line until 8.
*/
for(var i = “#”; i.length < 8; i += “#”){
console.log(i);
}

FIZZBUZZ
//fizzbuzz
for(let num = 1; num <= 100; num++) {
if((num % 3 == 0) && (num % 5 == 0)){
/*
here ^ ^ we are saying that numbers divisible by both 3 and 5 are
going to be replaced by fizzBuzz.
/
console.log(“fizzBuzz”);
}
else if (num % 3 == 0){
//number divisible by 3 are going to be replaced by fizz
console.log(“fizz”);
}
else if(num % 5 == 0){
//numbers divisible by 5 are going to be replaced by buzz
console.log(“buzz”);
}
else{console.log(num)}
/

we are logging all of the numbers that arent divisible by 3,5 or both.
it will continue to display all numbers up until 100.
*/
}
CHECKERBOARD
var size = 21;
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);

I can’t exactly explain checkerboard but I did go through these to try to be able to write them on my own. I am trying to wrap my head around these to figure out how to write them with ease and understand how these concepts work. Comment if you have any resources for practice!

Hello !
The way I wrote my answers might be a bit primitive, but that is how It came into my mind :slight_smile:

Exercice 1 : Looping a triangle

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

Exercice 2 : FizzBuzz

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

console.log (numOfTimes);
}

Exercice 3 : Chessboard

var numOfRows = 8;
for (var rows =0; rows<numOfRows; rows ++){
var toPrint = “”;
for (var column =0; column<numOfRows; column ++) {
if ((rows + column) % 2 == 0) {toPrint+="#";}
else {toPrint+=" ";}
}
console.log(toPrint)
}

  /* 1 - looping a triangle: */
  var niter = 7;
  var string1 = '';
  for(i=0; i<niter; i++){
    string1 = string1 + '*'
    console.log(string1)
  }

  /* 2 - FizzBuzz */
  for(var i=1; i<=100; i++){
      if(i % 3 == 0 && i % 5 == 0) {console.log('FizzBuzz')}
      else if(i % 3 == 0 && i % 5 !== 0) {console.log('Fizz')}
      else if(i % 5 == 0 && i % 3 !== 0) {console.log('Buzz')}
      else {console.log(i)};
    }

  /* 3 - Checkerboard */
  board_size = 8
  for(var i=0; i<board_size; i++){
          if (i % 2 == 0)
          {string1 = ''
          for(var j=1; j<=board_size/2; j++){string1 = string1 +' *'}
            console.log(string1)}
          else
          {string1 = ''
          for(var j=1; j<=board_size/2; j++){string1 = string1 +'* '}
            console.log(string1)}
        }

Triangle

var toPrint = “#”;
var hash = “#”;
var iterations = 100;

for (counter1 = 0; counter1 < iterations; counter1++){
console.log(toPrint);
toPrint += hash;
}

Fizz Buzz

var iterations = 101;
var fizz = “Fizz”;
var buzz = “Buzz”;

for(counter = 1; counter < iterations; counter++) {

var threeRemainder = counter % 3;
var fiveRemainder = counter % 5;
var remainderTotal = threeRemainder + fiveRemainder;

if (remainderTotal === 0) {
  console.log(fizz + buzz);
}

else if (threeRemainder === 0) {
  console.log(fizz);
}

else if (fiveRemainder === 0){
  console.log(buzz);
}

else {
console.log(counter);
}

}

Chess Board

var gridSize = 8;
var hashSpace = "# “;
var spaceHash = " #”;
var counter = 0;
var toggle = 0;

for (row = 0; row < gridSize; row++){
toggle = row % 2;

if (toggle === 1){

var toPrint = hashSpace;
for (counter1 = 1; counter1 < (gridSize / 2); counter1++){
  toPrint += hashSpace;
}

}

else {
var toPrint = spaceHash;
for (counter2 = 1; counter2 < (gridSize / 2); counter2++){
toPrint += spaceHash;
}
}

console.log(toPrint);
counter++;

}

Ex1: Looping Triangle:

Ex:2:FizzBuzz:

Ex:3:ChessBoard:

Triangule

function triangule(){
var num_row = 7;
for(var counter_row = 0;counter_row < num_row; counter_row++ ){
var simbol = “#”;
for (var counter_column = 0; counter_column < counter_row; counter_column++){
simbol+="#";
}
document.write(simbol + "<br ");
}
}

FizzBuzz

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

ChessBoard

function build_board(){
let size = 8;
let board = “”;
for(let row=0;row<size;row++){
for (let col=0;col<size;col++){
if((row+col)%2==0)board += “&nbsp”; //if row is odd, start with space
else board += “#”;
}
board += “<br”;
}
document.write(board);
}

1 Like

Apparently, my labor market value is still pretty low.for now, I will continue to practice.

Looping a Triangle
for (let line = “#”; line.length < 8; line += “#”)
console.log(line);

FIZZ BUZZ
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);
}

CheeseBoard 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);
[/quote]

//Looping a Triangle
var numRow = 7;
for (row = 0; row < numRow; row++) {
for (col = 0; col < row; col++) {
document.write("#")
}
document.write("#" + “
”)
}

//FizzBuzz
for (x = 1; x <=30; x++) {
if (x%15 == 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
var boardSize = 8;
var chessBoard = “”;
for (var col = 0; col < boardSize; col++) {
for (var row = 0; row < boardSize; row++) {
if ((row+col) % 2 == 0) {
chessBoard += " ";
}
else {chessBoard += “#”;
}
}
chessBoard += “\n”;
}
console.log(chessBoard);

One minor Q I have on FizzBuzz if it were written like this:

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

is why output += “Fizz” isn’t just output == “Fizz” ? Is this because the ‘+=’ is maintaining an increment increase similar to n++ in the first statement?
I’m gonna guess no to that question so if ‘+=’ is ‘x=x+y,’ does that mean that x is the 0 remainder value (AKA false Boolean) and y is Fizz || Buzz? Or is y the 0 and x is Fizz || Buzz? Does it matter?
But even that doesn’t entirely make sense to me…

I know this is probably a very simple Q (and I’m probably not even stating my question accurately)… but still curious…