Chapter 2 Exercises

Yes, that’s correct. The  symbol returns the value which the last expression entered evaluates to, even though we aren’t explicitly using the return keyword. Here is a link to a discussion about this, which I think is helpful, and it also uses a while loop as an example.
https://stackoverflow.com/questions/21820746/chrome-devtools-whats-this-arrow-meaning
The interesting thing to note about the example in the link, is that the final returned value (<· 4) is the same as the final value logged to the console (4). This is different to our original example, where it was higher: <· 14 (returned) as opposed to 12 (logged).This is because the final expression in our while loop body was num = num + 2 which evaluates to the num just logged (12) + 2 = 14). However, in the example in the link the final expression in the while loop body is i++ and not ++i . The position of the increment operator ++ is key because:

  • If placed BEFORE the operand (++i) the expression is evaluated and its value returned AFTER incrementing (i.e. the example in the link would console.log 4 and return  <· 5 ;
  • But when placed AFTER the operand (i++) the expression is evaluated and its value returned BEFORE incrementing.

You can read more about the increment operator in MDN Web Docs:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Increment

I hope this fully answers your question, and makes things much clearer for you :slight_smile:

2 Likes

Hey @CryptoMuscle, hope you are well.

Glado to know you solve it. At the start of the iteration of the first “for loop” will not fulfill the second one condition (which is z < y, z smaller than y, but if y is 0…)

If you have any more questions, please let us know so we can help you! :slight_smile:

Carlos Z.

Very insightful thanks @jon_m

1 Like

The only exercise that gave me some trouble was the chessboard one. I copied what i came up with below, but that was probably a long and confusing way of solving that exercise. After I solved it I looked at some of the other answers here and the code of some other solutions looks a lot cleaner than mine.
var bindingSize =8;
var rowNum =1;
var columnNum=1;
var x=’’;
var y=’’;
for (rowNum=1; rowNum<=bindingSize; rowNum++){
x=’’;
y=’’;
if (rowNum % 2==0){
for (columnNum=1; columnNum<=bindingSize; columnNum++){
if (columnNum % 2==0){
x += ’ ';
} else {
x += ‘#’;
}
}
console.log(x);
}
else {
for (columnNum=1; columnNum<=bindingSize; columnNum++){
if (columnNum % 2==0){
y += ‘#’;
} else {
y += ’ ';
}
}
console.log(y);
}
}

well the spacing looks horrible when I copied and pasted it. for clarification I was using single quotes on my strings so each time I set x and y back equal to empty strings, than as it loops through I am adding either a # or space character to the string.

    //fizbuzz

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

    //chessboard

let size = 8;
let result = '';
let row = 1;
  while (row <= size) {
let column = 1;
  while (column <= size) {
    if ((column + row) % 2 === 0) {
  result += " "
    } else {
  result += "#";
    }
  column += 1;
    }
  result += '\n';
  row += 1;
    }
console.log(result);

Here is the link to my Chapter 2 Exercises. This was fun! Exciting to learn new things, and that the code actually worked! Link to my Chapter 2 Exercises

  1. Triangle

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

  1. FizzBuzz

for(i = 0; i <=100; i++) {
var output = “”;
if (i % 3 == 0) output += “Fizz”;
if (i % 5== 0) output += “Buzz”;
console.log(output || i);
}

  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. Looping a triangle
    var numerales="#"
    for (var i=0; i<7;i++){
    console.log(numerales)
    numerales=numerales+"#"
    }

  2. FizzBuzz
    for (var i=0; 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);
    }

// i don’t know why if i put for (var i=0; i=100;i++) it leads me to an infinete loop, can anyone tell me why please?? :pray: :pray:

  1. B
    for (var i=0; i<101;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);
    }

  2. Chessboard
    var n=prompt(“Ingrese la dimension del tablero: “);
    var fila=””
    for (var i=0; i<n; i++){
    for (var j=0; j<n ;j++){
    if((i+j)%2==0) fila=fila+" “;
    else fila=fila+”#";
    }
    console.log(fila);
    fila=""
    }

1 Like

i = 100 , your for loop will goes in a infinite loop because even when i value is 100, is not a condition, is an assumption on the value, so even when i reach to 100, it will continue because is not a condition like "i must be equal or greater than…or less than…".

If you have any more questions, please let us know so we can help you! :slight_smile:

Carlos Z.

1 Like

Fizzbuzz was easy

for (numero = 1; numero <= 100; numero++){

if (number % 3 === 0 && numero % 5 === 0){
    console.log("fizzbuzz");
    continue;
}
if (numero % 3 === 0) {
    console.log("Fizz");
     continue;
    }

if (numero % 5 === 0) {
    console.log("Buzz");
    continue;
}
        
else {console.log(numero);}
    }

I had a lot of trouble with the checkerboard because the way it prints using console.log is very different from the way it prints using document.write.
I was able to create the 8-square checkerboard using this code:
for (row = 1; row <= 8; row++){

if (row % 2 === 1){
    console.log(" # # # # # # # #");
}
if (row % 2 === 0){
    console.log("# # # # # # # # ");
}

}
After 2 days of trying I had to look it up in the inputted version in the book, I don’t quite understand how the “+=” operator works. Lots of creative solutions in this thread.

1 Like

Yes, I wrote it wrong. I mean I== 100 or I=== 100, if “I” reaches the value of 100, it should stop like in other languages, but in JS it doesn’t work and I don’t understand its logic.

i = 100 is an assignment of value, but i == 100 is a comparison between the value of i and the value 100, is this correct?

1 Like

exactly, i = 100 means assign the value of 100 to variable i, while i == 100 means value of i equal to 100 (comparison), i === 100 means value of i exactly equal to 100.

Carlos Z.

1 Like

yes but it should work with “==” cause it is a comparison but i tried it and doesnt work :sweat: :sweat:

1 Like

I changed the exercises to output to the document instead of to the console.

  1. FuzzBuzz
      for (let i = 0; i <= 100; i++)
      {
          let printThis = "";

          if ((i/3 >= 1) && (i%3 == 0))
          {
            printThis += "Fizz";
          }
          if ((i/5 >= 1) && (i%5 == 0))
          {
            printThis += "Buzz";
          }

          if (!printThis)
          {
            printThis = i;
          }
          
          document.write(printThis + "<br>");
      }
  1. Chessboard
        let bindingSize = 8;
        let rows = bindingSize;
        let charOne = "&nbsp"; // non-breaking space
        let charTwo = "#";

        for (let i = 1; i <= rows; i++) {
            let printLine = "";

            for (let j = 1; j <= bindingSize; j++) {
                if (j % 2 == 0) {
                    printLine += charTwo;
                } else {
                    printLine += charOne;
                }
            }

            document.write(printLine + "<br>");

            // Switch chars
            [charOne, charTwo] = [charTwo, charOne];
        }
1 Like

Yeah, because for loops does not work as a comparation method, you can’t say “when i is equal to 100” (i == 100), so it will not run, for loop can use < , > , <=, >= which can be used to run until reach that condition, then you can have a if conditional inside of the for loop body to break the loop if the condition apply.

Example:

function start(){
  for (var i=0; i<100;i++){
     if(i == 50){
       console.log("BREAK LOOP");
       break;
     }
  console.log(i)
} 
}

Carlos Z.

1 Like

Thank you very much Carlos for taking the time and answering me twice the same question haha your explanation doesn’t leave any question. And the If method works great!

Lucas Botello

1 Like

Triangle:
for(let triangle = “#”; triangle.length <= 7; triangle += “#”)
console.log(triangle);

FizzBuzz:
for (let number=1; number <= 100; number++) {

        let output = "";

        if(number % 3 === 0) output += "Fizz";

        if(number % 5 === 0) output += "Buzz";

        console.log(output || number);
        }

Chessboard:
//Have to be honest…Googled several versions of this…
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

I have to give credit to … CompSciGuyIT a Prompt is used to ask the user to enter the desired size of the Board to create. I need to figure out how to make the “prompt” value entered is declared as the “Variable”. below is a copy of a fellow student’s answer I really like…thanks for sharing

let size = prompt("Enter the size of the board: ");
let board = “”;

        for (row = 0; row < size; row++) {
            for (column = 0; column < size; column++) {
              if ((column % 2 == 0 && row % 2 == 0)) {
                board += " ";
              } else if ((column % 2 == 0 && row % 2 == 1)) {
                board += "#";
              } else if ((column % 2 == 1 && row % 2 == 1)) {
                board += " ";
              } else {
                board += "#";
              }
            }
            board += "\n";
          }

          console.log(board);
1 Like

fizzbuzz: Here is a good breakdown that helped me learn fizzbuzz in 3 different ways, https://www.youtube.com/watch?v=Qb5owKFFn-g&t=3128s

function fizzBuzzC(value1,value2){
let returnValue = “”;
for (let i = 1;i<=100;i++){
// ? means evaluate to be true or false and do something after
returnValue += ((i%value1==0 ? ‘Fizz’ : ‘’) + (i%value2==0 ? ‘Buzz’ : ‘’) || i) + ’ ';
}
return returnValue;
}

chessboard: Here are a couple videos that helped me learn 2 ways to do chess board and really break it down in the second one.
https://www.youtube.com/watch?v=aLUwc_va6yA&t=1s
youtube.com/watch?v=JXyAuAsF1vw
//create a size variable = to 8
let size = 8

//create an empty string for Results
let result = ‘’;

// loop to create the rows
let row = 1;
while(row <= size){
//loop to create the columns
let column = 1;
while(column <= size){
//if column plus row is even
if((column + row) % 2 === 0){
//add an empty space
result += " ";
} else {
//else add an #
result += “#”;
}

column += 1;

}
// add a newline symbol /n to end current row
result += ‘\n’;
row += 1;
}
console.log(result);

2 Likes