Chapter 2 Exercises

//Looping a 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);	

}
//FizzBuzz
num_rows = 100
for(var row = 1; row <= num_rows; row++){
var fizz = row % 3;
var buzz = row % 5;
if (fizz == 0 && buzz == 0)
{
console.log(“FizzBuzz”);
}
else if (fizz == 0){
console.log(“Fizz”);
} else if (buzz == 0){
console.log(“Buzz”);
}
else{
console.log(row);
}
}

//Chessboard
var line = “”;
var columns = prompt(“Please enter number of columns”);
var rows = prompt(“Please enter number of rows”);

for(var row = 1; row <= rows; row++){
for(column = 1; column <= columns; column++){
if (row % 2 != 0){
if( column % 2 != 0){
line += " "
}
else
{
line += “#”
}
}
else
{
if( column % 2 == 0){
line += " "
}
else
{
line += “#”
}
}
}
line += “\n”
}
console.log(line);

Pyramid:

  var sign="#";
  var numberOfRows=7;
  for(var i=0;i<numberOfRows;i++)
  {
    console.log(sign);
    sign+="#";
  }

FizzBuzz:

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

}

Chessboard:

var height=8;
var width=8;
var board="";
for(var i=1;i<height+1;i++)
{
    if(i%2==1)
    {
        for(var y=1;y<width+1;y++)
        {
            if(y%2==1)
            {
                board+=" ";
            }
            else
            {
                board+="#";
            }
        
        }
    }
    else
    {
        for(var y=1;y<width+1;y++)
        {
            if(y%2==1)
            {
                board+="#";
            }
            else
            {
                board+=" ";
            }  
        
        }
    }
    board+="\n";
}
console.log(board);
1 Like
  1. FizzBuzz

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

Sorry, cant do " FizzBuzz" to work. Tried so many times still cant get it.

  1. ChessBoard

Best I can offer. Hope this code " print" the pattern out but still didnt work. Even cant understand the code solutions! Sorry.

for (n=0; n<7; n=n+2){ console.log("" + “” + "" + “” + “"); “\n”; console.log("" + "” + “” + “*” + “”);};

<script type="text/javascript">

/*Triangle Excercise*/
    triangle = ""
    for (i=0;i<7;i++){
      triangle+="#"
      console.log(triangle)
      }

/*FizzBuzz Excercise*/
    for (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 Excercise*/

    //define grid size

    let size = 8

    //define initial value of array (row 1, column 1)

    let v = ""

    //loop through rows

    for(r=1;r<=size;r++){

      //Determine value at each column index

      for(c=1;c<=size;c++){

        //Define criteria for even numbered rows

        if(r % 2 == 0) {
          if(c % 2 == 0) {v+=" "}
          else {v+="#"}
        }

        //Define criteria for odd numbered rows

        else {
          if(c % 2 == 0) {v+="#"}
          else {v+=" "}
        }
      }

      //add line break if column number = size

      v+="\n"

    }

    console.log(v)

  </script>

FizzBuzz solution

var output = [];

function fizzBuzz() {

for(var count = 1; count<=101; count++) {


if (count % 3 === 0 && count % 5 === 0) {
    output.push("FizzBuzz");
}

else if (count % 3 === 0) {
output.push(“Fizz”);
}

else if (count % 5 === 0) {

output.push("Buzz");

}

else { output.push(count);
    
}

}

console.log(output);

}

Looping Triangle

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

<script>
//Chessboard//
var board = "";
var size = "8";
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);

</script>
<script>
//FizzBuzz//

for(var numb = 1; numb <= 100; numb++){
var output = "";

    if (numb % 3 == 0) {output += "Fizz";}
    if (numb % 5 == 0) {output += "Buzz";}

    if (output == "") {output = numb; }

  console.log (output);

}

</script>

Truth be told, I got some aspects of the code right, but did need to use the google machine to complete the task. I will be satisfied when that will no longer be necessary.

1 Like

var num_rows = 7;

for(count = 1; count <= 100; count++){
  var toPrint = count;
  if (count % 3 == 0 ) {toPrint = "Fizz"};
  if (count % 5 == 0 && count % 3 != 0 ){toPrint = "Buzz"};
  if (count % 5 == 0 && count % 3 == 0 ){toPrint = "FizzBuzz"};
  console.log(toPrint)

As a seasoned programmer, I did not code these exercises. I did think about them, and then checked the solutions provided on the book’s website. I also reviewed several of other students’ answers. There are infinite solutions to each of exercises, but, of course, some are better (more optimal) than others. Some solutions showed what I consider to unique solutions that used interesting aspects of the language.

OK guys, back to coding… :slightly_smiling_face:

FizzBuzz

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

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

Thanks for your explanation! It clarified the exercise for me after spending an embarrassingly number of hours trying to figure this one out.

1 Like

These were all challenging for me. My brain has not been wired for coding, and I truly have a beginners mind where learning a coding language is concerned. It’s been fun and frustrating but there are some pieces starting to come together for me.

Excercise #1 Looping a Triangle

I just followed Ivan on this one so that I understand the logic in figuring this out using JS.

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

Exercise # 2 FizzBuzz

This was excruciating, the definition of insanity comes to mind. Looking at the solution helped of course, but I wanted to understand it and know why it worked.

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

var toPrint = “”;

if (counter % 3==0) toPrint += “Fizz”;

if (counter % 5==0) toPrint += “Buzz”;

if (counter % 3&&5==0) toPrint += “FizzBuzz”;

console.log(toPrint || counter);

}

Exercise #3 Chessboard
I used the concept of columns and rows to figure this out, which was limiting. My biggest challenge was how to get the chessboard, I know that was the point. Even after looking at the solution it wasn’t making sense to me. I went to this board and read a great explanation from another student that really clarified this for me.

var size = 8;
var toPrint = " ";

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

1 Like

FizzBuzz

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

	      if (number%3==0){
	        if(number%5==0){
	         console.log ("FizzBuzz");
	        }

	        else {
	         console.log ("Fizz");
	        }

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

ChessBoard

var number=8;
var row1="# # # #";
var row2=" # # # #";

for(i = 1; i<=number; i+=2)
{
console.log(row2);
console.log(row1);

}

1 Like

That´s great, Dana…

Don´t you feel good after this struggle? knowing that you did it? of course with the help from @Guactoshi explanation. :wink: I bet you learned so much from this.
Welcome to the life of programming. With struggle comes great knowledge.

Ivo

Here are my solutions:

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

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

}

}

var size = 20;

var rows = size;

var columns = size;

var toPrint = “”;

for(var i = 0; i< rows; i++){

for(var j =0; j<columns;j++){

    // is the row odd

    if(i % 2 == 1){

        // is the column odd

        if(j % 2 == 1){

            toPrint+=" "

        }else{

            toPrint+="#"

    }

}else{

    // the row is even

        if(j % 2 == 1){

            toPrint+="#"

        }else{

            toPrint+=" "

    }

    }

}

console.log(toPrint);

toPrint = "";

}

1 Like

looping a triangle:

<!DOCTYPE html>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>chapter 2 exercises</title>
</head>
<body>
    <script>
        hash = ""
        for(i=0; i<7; i++){
            hash = hash + "#"
            console.log(hash)
    </script>
</body>
</html>

FizzBuzz:

<!DOCTYPE html>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>chapter 2 exercises</title>
</head>
<body>
    <script>
for(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)
            }
            }
        console.log("done")
   </script>
</body>
</html>
type or paste code here

Chessboard:

<!DOCTYPE html>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>chapter 2 exercises</title>
</head>
<body>
    <script>
 size = 8;
        chess = "";
        for(x=1; x<=size; x++){
            for(y=1; y<=size; y++){
                if(x%2==0){
                    if(y%2==0){chess = chess + "#";}
                        else {chess = chess + " ";}
                    }
                else{
                    if(y%2==0){chess = chess + " ";}
                        else {chess = chess + "#";}
                    }
        }
        chess = chess + "\n";
        }
        console.log(chess);
   </script>
</body>
</html>
2 Likes

@Fabrice @ivga80

console.log() is not working for me. Therefore used document.write() instead. \n is also not working for me. Hence I am not sure whether chessboard exercise is correct, as I could not test it successfully.

Looping Triangle
<script>
    //code for looping triangle
      var num_rows = 7;
      var toPrint ="#";
      for (var row = 0; row < num_rows; row++) {
       document.write(toPrint + "\n");
      toPrint += "#";
       }
    </script>

Fizzbuzz
<script>
//code for fizzbuzz
for (var counter = 1; counter <= 100 ; counter++) {
         if ((counter%3 ==0) && (counter%5 != 0))  {
         document.write(counter + "Fizz + \n");
           }
          if ((counter%5 ==0) && (counter%3 != 0)) {
         document.write(counter + "Buzz + \n");
          }
          if ((counter%3 ==0) && (counter%5 ==0)){
          document.write(counter + "FizzBuzz + \n");
            }
        }
</script>

Chessboard
  <script>
    //code for chessboard
    var size = 8;
var toPrint = "";
  for (var row = 0; row < size; row++) {
      for (var col = 0; col < size; col++) {
           if ((row + col) % 2 == 0) {
                 toPrint += " ";
                 document.write(toPrint);
                } else {
                  toPrint += "#";
                   document.write(toPrint);
                               }
                           }
                      toPrint += "\n";
                }
   </script>

 or paste code here

Wow. I found the checkerboard a proper headache, but I’m sooo proud I did it! The others not too bad.

While loops, If else statements, and after lots of googling - string.charAt(string.length -1) were the saving grace for me.

A very tough exercise for newcomers but ultimately confidence building and rewarding.

Ive since seen more ‘compact’ and ‘effective’ code here by others, but I refused to look at any solutions until I had got it working my own way first. In time I will be able to code tidier myself.

// CHECKERBOARD

  // += appends onto the variable. ie. string += hash

  var cols = 15;  // value can be changed

  var rows = 15;  // value can be changed

  var space = " ";

  var hash = "#";

  var string = "";

  var colsCount = 0;

  var rowsCount = 0;

  var string = space;

  while (rowsCount < rows) {

    // new row string starts with space

    if (string === space) {

      while (colsCount < cols - 1) {

        // if last string char is a space

        if (string.charAt(string.length - 1) === space) {

          string += hash;

        } else {

          string += space;

        }

        colsCount++;

      }

      console.log(string);

      string = hash;

      rowsCount++;

      colsCount = 0;

    }

    // new row string starts with hash

    else {

      while (colsCount < cols - 1) {

        // if last string char is a hash

        if (string.charAt(string.length - 1) === hash) {

          string += space;

        } else {

          string += hash;

        }

        colsCount++;

      }

      console.log(string);

      string = space;

      rowsCount++;

      colsCount = 0;

    }

  }
1 Like

Hi @Antonio_Andara
I think your “for loop” in the triangle exercise missed a closing bracket }
:wink:

Hi @simplyprado
When you say console.log() is not working, do you have an error showing up in your browser console ?
console.log() is standard and should work.

If you want to add a new line and print it to the page you can use :

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

I tried your code in the console and it works :slight_smile: