Chapter 2 Exercises

  1. Triangle.
    //I came into the exercises absolutely overwhelmed by all new information. I had to go through MANY answers of other classmates, first typing their code out manually to hammer the functionalities into my working memory. After many hours I finally reached a point where I was able not only to somewhat read the code but even when I tried running code that wasn’t functional managed to see what someone meant to do and debug it. Proud over my quarantine progress and ready to post the solutions as I’ve found them most understandable//

for(var row = 0; row <7; row++)
{
var hash = “#”;
for (var column = 0; column < row; column++)
{
hash = hash + “#”;
}
console.log(hash);
}

  1. FizzBuzz
    Still have a hard time understanding the math, if x, which is 1 is divided by 3 how does it ever turn to zero? 3/1 = 1, if anyone could explain this to me I’d be grateful.
    Also I have still not understand how {} really work. They’re basically just in the right place because of endless trial and error.

for(var x = 1; x < 101; x++)
{
if (x % 3 == 0 && x % 5 == 0){
console.log (“Fuxsbox”);
} else if(x % 5 == 0) {
console.log(“Box”);
} else if(x % 3 == 0) {
console.log(“Fuxs”);
} else
console.log(x);
}

  1. Chessboard

let size = 8;
let toPrint = “”;
for (let row = 0; row < size; row++) {
for (let col = 0; col < size; col++) {
if ((row + col) % 2 == 0) {
toPrint += " ";
} else {
toPrint += “#”;
}
}
toPrint += “\n”;
}
console.log(toPrint);

1 Like

Pyramid-

        for(height=0; height < 7; height++ ){
          let pyramid = "";
          for(width=0; width <= height; width ++) {
              pyramid += "#";
          }
          console.log(pyramid + "\n");
        }

Fizzbuzz-

   for(var a=0;a<50;a++){ 
      if(a%15==0) console.log("Fizzbutt");
      else if(a%5==0) console.log("Butt");
      else if(a%3==0) console.log("Fizz</br>");
      else(console.log(a))
   }

Chessboard-

var board ="";
var parameter =8;{
     for(var y=1;y<=parameter;y++){
        for(var x=1;x<=parameter;x++){
            if((x+y)%2==0) 
                board += " ";
            else board += "#";
        }
         board += "\n";
     }}
1 Like

Hi. Chakingo

These are called curly brackets {} and it’s inside the { you can define what you want the function or statement to execute }. :slightly_smiling_face:

let’s take the pseudo IF statement:

if (currentBtcPrice < lastBtcPrice) { 
 console.log("buyMoreBtc");
}

This pseudo code above is translated to:

if (statement) {
    execute the code inside the curley brackets;
}

I hope this cleared things up for you.
Nice work with your learning progress, it shows in your code. :wink:

Ivo

Thanks man! I kind of followed so far, but the thing is that often it seems that there are curly brackets inside curly brackets, and sometimes they are opened but not closed and sometimes it seems code won’t run unless there is a certain amount of curly brackets at the end. My impression is that some programs needs
}
}
}
at the end to run correctly, can you help me understand why that is?

Hi,

As a beginner I found this quite challenging… Can I have more advice on how to get more practice on this? Perhaps some similar exercises so I can practice.
Many thanks

1 Like

Fizzbuzz

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

        var word = "";


           if (x % 3 == 0)
        {
          word += "Fizz";
        }
           if (x % 5 == 0)
        {
          word += "Buzz";
        }
              else
        {
          word = x;
        }

      console.log(word);
    }

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

Can anyone help please? I spent so many hours by trying to figure out how to code that triangle in console without any success. I gave up and went to the book and copied their code and it came out with “undefined” same as my other codes. When I try with numbers it seems working when I try “triangle” it’s undefined. Tried in every single browser results are the same. Can’t get my head around why is that.

for( var line = "#"; line.lenght < 8; line += "#")
  console.log(line);
2 Likes
  1. Triangle
 var num_rows = 7;
    for(var row = 0; row < num_rows; row++){
      var toPrint = "#";

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

    }
  1. FizzBuzz
 for (var x= 1; x<=100; x++){

      if (x % 15 == 0)
        console.log("FizzBuzz");
      else if(x % 5 == 0)
        console.log("Buzz");
      else if(x % 3 == 0)
        console.log("Fizz");
      else console.log(x);

  }
  1. Chessboard
  var size = 8;

  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);
2 Likes

Hi.
Nested Scopes and loops is the reason you may see the curly-brackets at the end of someones code

}
}
}

So if you see a closing bracket, you will always be an opening bracket above. curly-brackets are used in pairs, just like (), [] and {} . :+1:t2:

This is from the book.

Defining Functions.
The function body of a function created this way must always be wrapped in braces, even when it consists of only a single statement.

A function can have multiple parameters or no parameters at all. In the following example, makeNoise does not list any parameter names, whereas power lists two:

const makeNoise = function() {
  console.log("Pling!");
};

makeNoise();
// → Pling!

const power = function(base, exponent) {
  let result = 1;
  for (let count = 0; count < exponent; count++) {
    result *= base;
  }
  return result;
};

console.log(power(2, 10));
// → 1024

Nested scope
JavaScript distinguishes not just global and local bindings. Blocks and functions can be created inside other blocks and functions, producing multiple degrees of locality.

For example, this function—which outputs the ingredients needed to make a batch of hummus—has another function inside it:

const hummus = function(factor) {
  const ingredient = function(amount, unit, name) {
    let ingredientAmount = amount * factor;
    if (ingredientAmount > 1) {
      unit += "s";
    }
    console.log(`${ingredientAmount} ${unit} ${name}`);
  };
  ingredient(1, "can", "chickpeas");
  ingredient(0.25, "cup", "tahini");
  ingredient(0.25, "cup", "lemon juice");
  ingredient(1, "clove", "garlic");
  ingredient(2, "tablespoon", "olive oil");
  ingredient(0.5, "teaspoon", "cumin");
};

The code inside the ingredient function can see the factor binding from the outer function. But its local bindings, such as unit or ingredientAmount, are not visible in the outer function.

The set of bindings visible inside a block is determined by the place of that block in the program text. Each local scope can also see all the local scopes that contain it, and all scopes can see the global scope. This approach to binding visibility is called lexical scoping.

I hope this explains it better. :+1:

Ivo

1 Like

Hi, I think I can help you out with this issue. :man_teacher:
[spoiler]it’s length, my friend.[/spoiler]

Been there, done that, @Luca_del_Grosso did it last. :wink:

Ivo

Try this site…
https://www.w3schools.com/js/default.asp

87938876_485221338839185_9168911387685027840_n

FizzBuzz

Ok I did manage to figure out i needed the % remainder symbol, and ofcoz use a loop, but something is wrong with my ATOM, because when I try to open my new file FizzBuzz.html, then my page is blank, but when I run the code in the console I get the right result.

  <script type="text/javascript">

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


  </script>

Hi, Try to change console.log(); to document.write();
It should work like this:

<script>
for (var i=1; i < 101; 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>");
  }
</script>

Ivo

1 Like

Woow haha it worked, thanks. I feel so dumb right now. How did I not see that? lol

2 Likes

Is it only me who couldn’t solve the chessboard? I have spent the whole afternoon trying to solve it, but didn’t get anywhere with this one.
I feel like this course is a bit hands off. Need more explanation on what’s what and why.

1 Like

Exactly! I was struggling with the Chessboard too. I don’t feel like we are well taught how to think efficiently, in order to be able to solve that exercise. Maybe I am dumb, but this course was advertised for anyone without any kind of programming experience. @ivan @filip

2 Likes

Ok I tried a lot, but could not get by myself, or actually I because as an developer google is my best friend…This solution was one of many, but I like the layout.

var chessBoard= " ",
size = 8,
c;
for(var i = 0; i < size; i++) {
c=i%2 ? ‘# ’ : ’ #’;
for(var j = 0 ; j < size/2; j++){
chessBoard+= c;
}
chessBoard+= ‘\n’;
}
console.log(chessBoard);

1 Like

Hi Zoltan.
Please spend some time reading the posts above. A lot of people struggle with this first exercise, But we all got trough and its hard for a reason, my friend.
Just hang in there and use the resources available to you.
Hint, hint. There is no need to reinvent the wheel, just don’t copy&paste code from others, type it yourself and try to understand why it’s done like it is.

I hoped it helped you a little on your way.

And yes, you can learn this as a non-programmer, Just ask the people at the end of this course. I’ll link you the topic and you can ask those people if any of them knew how to program before they started.
Here you go, ask them in this post, maybe their answers can get your motivation up? :wink:

Ivo

2 Likes

Thanks Ivo, you are right, I’ll push more.

1 Like

Chessboard

By including a for loop inside of another for loop, we are iterating through the numbers added to the column variable. Running the second for loop( let’s call it “column loop”), generates a number 1-8. Each of these numbers then are added to the number generated by the first for loop (let’s call it “row loop”). The initial number that is generated by the “row loop” is 1. That number then is iterated through the numbers generated by the “column loop” and checks if % 2 == 0 to give a True value(if the number is even) or a False value (if the number is odd). If the Boolean is True, it will print “ “ to the console, if it’s False, it will print “#”.
When the number of iterations reach 8, the ‘board += “\n”;’ executes onto a new line and exits the “column loop”, and adds a number(row++) to “row”. At this point row will be equal to 2. We are entering into another iteration through the “column loop”, but as this time the row is set to an even 2, adding the first column number which is 1 to it, will produce an odd number % 2 == 0 will return False, so the new row will be starting with “#”.
This iteration continues until the “row loop” returns False, meaning, not less than or equal to the size variable.

1 Like