Chapter 2 Exercises

:neutral_face::expressionless:…

I wanted to protest. No it works! Error! ?!?Theres sats stacked neatly but alas there it was Capital C. Cant blame spell Check either

:man_shrugging:t5:

details, teamwork, visual metaphor stands

(cracks open book)

1 Like

Definitely needed to google a few things to work out these problems. Modulo is one of those things from school that I never understood the importance of…until now. Here’s my solutions:

Looping a triangle

let hep = "#";
for (let hash = 0; hash <= 6; hash++) {
  //console.log(hash);
  console.log(hep);
  String(hep += "#");
}

FizzBuzz

for (let soda = 1; soda <= 100; soda++) {
//use == for comparison, use = for assignment
  if ((soda % 3 == 0) && (soda % 5 == 0)) {
      console.log("FizzBuzz");
      }
  else if (soda % 3 == 0) {
      console.log("Fizz");
  }
  else if (soda % 5 == 0) {
      console.log("Buzz");
  }
  else {
    console.log(soda);
  }
}

Chessboard

let height = 6; //height is the height of pattern
let width = 12; //width is the width of pattern
let chessboard = String("");
for (let rows = 1; rows <= height; rows++) {
  for (let col = 1; col <= width; col++) {
    if ((rows % 2 == 0) && (col % 2 != 0)) {
       chessboard += "#";
    }
    else if ((rows % 2 == 0) && (col % 2 == 0)) {
       chessboard += " ";
    }
    else if ((rows % 2 != 0) && (col % 2 == 0)) {
      chessboard += "#";
    }
    else {
      chessboard += " ";
    }
   }
   chessboard += "\n";
}
console.log(chessboard);  
1 Like

Great solutions @qh.w! :+1:

Well done for adapting them so that the output is displayed on the web page, instead of logged to the console :ok_hand:

Just a couple of observations…

You can slim down your Looping a Triangle and make it a bit more concise:
(Comments show removed or modified code from your original version)

document.write("<strong>Looping a triangle</strong></p>");
let s = "";    // let s, s1 = "";
for (let i = 1; i <= 7; i += 1) {
    // s = ""
	for (let j = 1; j <= i; j += 1) {
		s += "#";
	};
	s += "<br>";
    // s1 += s;
};
document.write(s);  // document.write(s1);

What do you think? Feel free to disagree :slight_smile:

Chessboard
Do you think we need to make the offset (in terms of the alternating squares) greater between the rows? How about changing:

str += "&nbsp";
// to
str += "&nbsp ";
// ...or something similar?

Keep up the great work! You’re making great progress! :muscle:

@jon_m Thank you very much for the feedback. Unfortunately, I don not have any development background, I am going to relearn the JavaScript course to cement the knowledge and will do the quiz again.

1 Like

ChessBoard:

let result = "";
// create rows
  for (let row = 0; row < 8; row++){
// create column
    for (let column = 0; column < 8; column++){
       if ((row + column) % 2 === 0) {
        result += " ";
      }
      else {
          result += "#";
        }
   }
    //add new line
    result += '\n';
  }
console.log(result);

I’ve failed many time so i have to look a bit more from some one else :shushing_face:

2 Likes

Hi @ashishc!
You’re doing really well if you were a complete beginner before starting this course! It’s very intensive and you learn a lot very quickly. Going back and repeating certain parts and spending time experimenting and doing your own research will really help you to cement your knowledge and build your confidence. I highly recommend that approach. There is also a wealth of information here in the forum. I also recommend you spend time reading through other students’ posts and the reviews and feedback they have received.

Keep on learning! :smiley:

;FizzBus

let num;
for (let number=1;number<=100; number++){
if((number%3==0)&&(number%5==0)){num=“FizzBuzz”;}
else{ if(number%3==0){num=“Fizz”;}
else{ if(number%5==0){num=“Buzz”;}
else { num=number;}}
}
console.log(num);

1 Like

Looping a Triangle

      // Looping a Triangle using a while loop with console.log

      var hashTag = "#";
      let x = 0;
        while (x < 10) {
          console.log(hashTag);
          x++;
          hashTag += "#";
        }

      // Looping a Triangle using a for loop with document.write

      var hashTag = "#";
      for (x = 0; x < 7; x++) {
        document.write(hashTag + "<br />");
        hashTag += "#";
      }

FizzBuzz

      // FizzBuzz Exercise using a for loop and console.log

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

console.log(“And because that was so much fun, here it is again:)”)

      // FizzBuzz Exercise using a while loop and console.log

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

Chessboard

I have to admit that I did not manage to work this one out. At least not the way the book asks it, which is via console.log. After trying for over a week I decided to write a program using document.write instead. The program works beautifully for any number used in the variable size.

There was one minor adjustment however. I substituted the " " for “0”. Document.write doesn’t read a space when it appears at the beginning of a row - In my case it simply pushed the hashtag to the front. You can use any other “visible” character, it works just as well.

One last point: I tried to convert the program into console.log mode, substituting the break line for \n, and the output is all vertical. I did not manage to find a way to output the rows horizontally. What am I missing?

      var size = 8;
      var hashTaG = "#";
      var blank = "0";

      for(a = 0; a < size; a++) {
        if(a % 2 == 0) {
          for(x = 0; x < size; x++) {
            if(x % 2 == 0) {
              document.write(blank);
            }
            else {
              document.write(hashTaG);
            }
          }
        }
        else {
          for(x = 0; x < size; x++) {
            if(x % 2 == 0) {
              document.write(hashTaG);
            }
            else {
              document.write(blank);
            }
          }
        }
          document.write("<br />");
      }
1 Like

@jon_m Thank you for the encouragement Jon, good to know that my efforts are being noticed. @ivan Ivan and his team is doing a great work in the blockchain space. Thank you !

1 Like

Hi jon_m, thanks for the pointers!

I made the horizontal spaces 3 spaces and # wide to make the board more uniform. It looks good in console, but document.write does not add the space at the beginning and only one space between each black square for some reason? The code looks like this:

type or paste code here
```<html>

<head>
<title>This is a great javascript testing site</title>
</head>
<body>

  <h1> Amazing Chessboard creater -70%, only 99,95€ </h1>

  <script>

  // convert string to number 10-system
  var sizeOfBoard = parseInt(prompt("Give the size of your board",0),10);
  var boardLineEven = "";
  var boardLineUneven = "";

  for(var counter = 0; counter < sizeOfBoard; counter++){
    if (counter % 2 ===0){
      boardLineEven += "   ";
      boardLineUneven += "###";
    }
    else {
      boardLineEven += "###";
      boardLineUneven += "   ";

    }
  }



  for(var counter = 0; counter < sizeOfBoard; counter++){
    if (counter % 2 ===0){
      console.log(boardLineEven);
        document.write(boardLineEven + "<br>");
    }
    else {
      console.log(boardLineUneven);
      document.write(boardLineUneven + "<br>");
    }
  }

  </script>

</body>

</html>
1 Like

This is excellent, @Omar! :smiley:

You’ve made great progress, and I can definitely see that you’ve…

Just a couple of very minor points:

Looping a Triangle

You have the number 7 (for the number of rows) assigned to var pyramid as a string. This doesn’t actually throw an error, as I think the for loop condition coerces it to a number value automatically. But it’s good to get into the habit of storing the appropriate value type for the operation we want to perform with the value, otherwise it could lead to a bug during any further development of the program.

var pyramid = 7;

Chessboard

If you run your code with this line as it is, you will notice that the pattern logged is not correct.
I’m not sure if it’s just a copy-and-paste slip, but it’s easily corrected by removing the white space from either side of the hash i.e  change   " # "   to   "#"

Keep up this great momentum! :muscle:

Hey @Li_Sun,

Nice! :ok_hand:

I stand corrected :slightly_smiling_face:
Thank you for demonstrating how it can be done.

Triangle Loop:

for(var hash = “#”; hash.length < 8; hash += “#”){
console.log(hash);
}

FizzBuzz:

for( var 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);}
}

or

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

ChessBoard:

let size =8;
let space="";

for(let i = 0; i < size; i++){
for(let j = 0; j < size; j++){
if ((i + j) % 2 === 0) {
space += " ";
} else {
space += “#”;
}
}
space += “\n”;
}
console.log(space);

Really difficult for a complete beginner, had to go back a restudy multiple times, go through different course. All that extra study helped me start to grasp an understand how this should work and even still I had to look at the solution of the Chessboard to get a bit of help. However I’ve notice great improvement in my knowledge. I guess it’s all about being patient and keep on trying constantly.

1 Like
  1. Looping A Triangle:
t<script> //src= "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.">
      var num_rows = 8;
      for (var row =0; row < num_rows; row++)   {
        //console.log("row number " + row);
        // won't work!   document.write (" row number " + row);
        var toPrint = "#";

        for (var column = 0; column < row; column++){
          toPrint+= "#";
        }
          //document.write(toPrint); Once again, all prints in one line.
        console.log(toPrint);
      }

    </script>
  1. Fizz Buzz:
<script>
      var num = 1; //if you use 0 on this line and the next, the program will start with
      //Fizz Buzz FizzBuzz - not a prob, but if you use 1, it just begins as it should
      for(num = 1; num < 101; num++){

        if (num % 3 == 0)
        console.log("Fizz");
        if (num % 5 == 0)
        console.log("Buzz");

        if (num % 3 == 0 && num % 5 == 0)
        console.log("FizzBuzz");

        else
        console.log(num);
        }


    </script>

Chessboard - this was difficult - I had to find help on the internet.

  <script>

    var board = "";
    var size = 8;
    for(var y = 0; y< size; y++){
    //  board += y; //allows display of vertical numbering
    for(var x = 0; x< size; x++){
        if((x + y) % 2 == 0) {
        board += " "; // + concatenates the hashes and spaces
        }

        else {
        board += "#"; // + concatenates the hashes and spaces
        }


      }
      board += "\n";
    }
    console.log(board);

      </script>
1 Like

Triangle Loop

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

Fizz Buzz Loop

for(let num = “1”; num <= 100; num++){
let toPrint = “”;
if (num%3==0) toPrint += “Fizz”;
if (num%5==0) toPrint += “Buzz”;
console.log(toPrint || num);
}

ChessBoard Loop

let width = 8;
let height = 8;
let board = “”;

for (let y = 0; y<height; y++){
for (let x = 0; x<width; x++){
if ((x+y)%2==0) board += " ";
else board += “#”;
} board += “\n”;
} console.log(board);

1 Like

fuzzbuzz

for (let 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);
}
}

chessboard

x=8;
for (var i=1;i<=x;i++){
text="";
for(var j=1;j<=x;j++)
{
if((i+j)%2==0){text=text+" “} else {text=text+”#"};
};
console.log(text);
}

1 Like

Great solutions @Bette! :muscle:

I really like how you’ve incorporated the flexibility to have an unequal number of rows and columns in your Chessboard :+1:

Just one observation…
In your Chessboard, you can condense your conditional execution from 4 branches into just 2, as follows:

if ((rows + col) % 2 == 0) {
   chessboard += " ";
}
else {
   chessboard += "#";
}

Your solution is perfectly fine… but it’s always good to condense IF our code still maintains its clarity, which I think, here, it does. But please feel free to disagree — these things are never 100% black and white… sorry, chessboard pun was unintentional :wink:

Don’t worry @kmilo_Mart, your secret is safe with me…oooops!.. maybe not… sorry :wink:

Seriously though, that’s absolutely fine to end up looking at other people’s solutions and the model answer, as long as you have given it your best shot first. That’s the most important thing — to really spend time wrestling with it yourself first. Then, if you had to get some help, before moving on, make sure you analyse the solution(s), and kind of work backwards from there. You can learn a lot by working out what the solution does differently and how to go about “bridging the gap” from what you managed to do (or not) on your own. As long as you understand the code you’re finally posting, that’s job done! :slightly_smiling_face:

Well done for taking your time and not rushing. You’ll be learning loads and making more progress that way! :muscle:

1 Like

Thanks, Jon!
My solution looks pretty clunky next to your very succinct one. I like how you condensed everything to one test. It shows if you take a little more time up front thinking about the problem to be solved you can find a sleeker solution.
Love the pun, btw!

1 Like

Often, the sleeker solution comes later. A lot of the time you need to create a more long-winded version first, but then the key is to not leave it at that, but
spend some time thinking about how you could trim it back. That review and reflection stage is so important. After a while you find more and more that the succinct solution comes to you earlier, as your brain automatically skips some of the steps to get there.

1 Like