Chapter 2 Exercises

Hi.

So I also managed to successfully complete 3/3 exercises.

So, Looping triangle;

document.write("<p>Excersise 1 - Looping triangle:<br />");
    for(let pyramid="#";pyramid.length<7;pyramid+="#"){
      document.write(pyramid);
      document.write("<br />");
    }
    document.write("</p>");

FizzBuzz;

    document.write("<p>Excersise 2 - FizzBuzz:<br /");
    for (let number=0;number<=100;number++){
      if(number%3 == 0 && number%5 == 0) document.write(number + " - FizzBuzz - Divisible by 3 and 5");
      else if(number%3 == 0) document.write(number + " - Fizz - Divisible by 3");
      else if(number%5 == 0) document.write(number + " - Buzz - Divisible by 5");
      else document.write(number);
      document.write("<br />");
    }
    document.write("</p>");

and finally Chessboard. I tried to fancy it up a little and do some extra steps to learn and experiment. By looking at oher examples, I see I could have done it much cleaner. The code;

  document.write("<p>Excersise 3 - Chessboard:<br />");
    let boardLenght=Number(prompt("We're creating a square chessboard. Enter the desired board length - number of fields per side (e.g. enter 8 for board size 8x8)."));
    if ((boardLenght > 0) && (boardLenght % 1 == 0) && (boardLenght != NaN)) {
      let whiteField="&nbsp";
      let blackField="#";
      for (let rows=1;rows<=boardLenght;rows++){
        if(rows%2 == 0) {console.log(rows +" = even row")} else {console.log(rows +" = odd row")};
        if(rows%2 == 0) // if it is an odd row, it should start with a black field
          for (let evenRowColumn = 1;  evenRowColumn <= boardLenght ; evenRowColumn++) {
            console.log("Even row executed: row " + rows + ", column " + evenRowColumn);
            if(evenRowColumn%2 == 0) {document.write(whiteField); console.log("    White field")}
            else {document.write(blackField); console.log("    Black field")};
            }
        else // if it is an even row, it should start with a white field
          for (let oddRowColumn = 1;  oddRowColumn <= boardLenght ; oddRowColumn++) {
            console.log("Odd row executed: row " + rows + ", column " + oddRowColumn);
            if(oddRowColumn%2 == 0) {document.write(blackField); console.log("    Black field");}
            else {document.write(whiteField); console.log("    White field");};
        }
        document.write("<br />");
      };
    }
    else alert("The number you have entered either isn't a positive number, isn't a whole number or is not a number at all. To try again, please reload the page.");
document.write("</p>");

Thank you.
J.

My version of the 3 Exercises:

Looping 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

  var Fizz;
  var Buzz;
  for (var counter = 1; counter < 100; counter++){
    Fizz = counter % 3;
    Buzz = counter % 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(counter);
    }
  }

Chessboard

  var chessboard = " ";
  var scale = 8;
  for (var line = 0; line < scale; line++){
    var row = 0;
      while (row<scale){
        chessboard += "# ";
        row++;
      }
    chessboard += "\n";
    if (line%2 == 1){
      chessboard += " ";
    }
  }
  console.log(chessboard);

Probably not the shortest version, but at least I can follow my steps this way at any time :smiley:

TRIANGLE

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

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

CHESSBOARD

 let length = 8;

  let board = " ";

  for (let y = 0; y < length; y++) {
    for (let x = 0; x < length; x++) {
      if ((x + y) % 2 == 0) {
        board += " ";
      } else {
        board += "#";
      }
    }
    board += "\n";
  }

  console.log(board);

ALL WORKING

Triangle Loop:

let charPound = "#";
for (let index = 0; index < 8; index++) {
    console.log(charPound.repeat(index));  
}

FizzBuzz

for (let numStart = 0; numStart<100; numStart++) {
    switch (true) {
        case ((numStart>0) && (numStart%3 == 0)):
            console.log("Fizz");
            break;

        case ((numStart>0) && (numStart%5 == 0)):
            console.log("Buzz");
            break;

        default:
            console.log(numStart);
    }    
}

Chess Board

let size = prompt(Number("How many rows?")), board = "# # # #";
for (let count = 0; count < size; count++) {
    if (count%2==0) {
        console.log(" " + board)
    } else {
        console.log(board);
        }
}

Only problem is if you want an odd amount of lines (since you combined the two lines into a single string). Here is how I solved it, which allows for an even or odd amount.

let size = prompt(Number("How many rows?")), board = "# # # #";
for (let count = 0; count < size; count++) {
    if (count%2==0) {
        console.log(" " + board)
    } else {
        console.log(board);
        }
}

FizzBuzz

  for (let number=1; number<=100; number++){
    if (number%3==0 && number%5!==0){
      console.log('fizz');
    }else if (number%5==0 && number%3!==0){
      console.log('Buzz');
    }else if(number%5==0 && number%3==0){
      console.log('fizzBuzz')
    } else {
      console.log(number);
    }
  }

Chess Board

    let displayValue="";
    let columnRow = 8;
    for (let y=0; y<columnRow; y++){
      for(let x=0; x<columnRow; x++) {
        displayValue += (x + y)%2==0 ? " " : "#";
    }
      displayValue += "\n";
    }
  console.log(displayValue);

FizzBuzz

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

if (counter % 3 === 0 && counter % 5 === 0) {
  document.write ("FizzBuzz" + "<br>");
}
else if (counter % 5 === 0 && counter % 3 > 0) {
  document.write ("Buzz" + "<br>");
}
else if (counter % 3 === 0) {
  document.write ("Fizz" + "<br>");
}
else  {
  document.write (counter + "<br>");
}

}

Chessboard

let rowsNum = 8;

let output1 = " #".repeat(rowsNum);
let output2 = "# ".repeat(rowsNum);

for (var row = 1; row < rowsNum; row++) {

if (row % 2 == 0) {
console.log (output1);
}
else {
console.log (output2);
}
}

FizzBuzz

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

Chessboard

var size = 8;
let line = “”;

for (let row = 1; row <= size; row++){
if (row % 2 == 0){
line = “#”;
}else{
line = " ";
}
while (line.length <= size){
if(line.charAt(line.length-1) == “#”){
line += " ";
}else{
line += “#”;
}
}
console.log(line);
}

FizzBizz Solution

for (var i = 1; i <= 100; i++) {
if (i % 5 === 0 && i % 3 === 0) {
console.log(‘FizzBuzz’);
}
else if (i % 5 === 0 ) {
console.log(‘Buzz’);
}
else if(i % 3 === 0) {
console.log(‘Fizz’);
} else {
console.log(i);
}

Chess Board Solution

var row = ‘# # # #’
for(var i = 0; i < 8; i++) {
if(i % 2 === 0)
console.log(’ ’ + row);
else
console.log(row + ’ ');

    console.log('\n');
  }

1.Looping a triangle:
for (var raw = 0; raw < 7; raw++) {
var TextToDisplay="#";
for (var col = 0; col < raw; col++) {
TextToDisplay+="#";
}
console.log(TextToDisplay);
}

  1. FizzBuzz:
for (var n = 1; n <=100; n++) { if (((n%3)==0)&&((n%5)==0)) { console.log("FizzBuzz"); } else if ((n%3)==0) { console.log("Fizz"); } else if ((n%5)==0) { console.log("Buzz"); } else console.log(n); } 3. ChechMate: let size =8; var string = ''; for (var r = 0; r <size; r++) { for (var c = 0; c < size; c++) { if ((r+c)%2==0) { string+=' '; } else string+='#'; } string+='\n'; } alert(string); I first drew this in search for a more elegant solution than conditional execution: 01234567 0 # # # # 1 # # # # 2 # # # # 3 # # # # 4 # # # # 5 # # # # 6 # # # # 7 # # # #

FizzBuzz solution

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

}

Took me almost an hour to get the Chess board working correctly with any number you enter, but here it is

var gridSize = Number(prompt(“How big you wanna go?”));
let line = “”;

for(let row = 0; row<gridSize; row++){
  if(row%2 ==0){
    line = " ";
  }
  else{
    line = "#"
  }
   while(line.length<(gridSize*2)){
     if(line.charAt(line.length-1) == "#"){
      line += " ";
    }else{
      line += "#";
    }
   }
    console.log(line);
}

Hello, I was wondering if you would be able to explain to me how you use the } in JavaScript please? I understand the if and else stuff but where the } goes is preventing me from moving forward as I don’t understand where it should go? Many thanks

TRIANGLE LOOP
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

function fizzBuzz(){
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);
}
}
}
fizzBuzz();

CHESSBOARD LOOP

var rows = 4;
var cols = 4;
for(var i=1; i<=rows; i++){

console.log(" # ");

}
for(var j=1; j<=cols; j++){
console.log("# ");
}
for(var i=1; i<=rows; i++){

console.log(" # ");

}
for(var j=1; j<=cols; j++){
console.log("# ");
}

This was a tricky one for me. I understand what I need to do, and have tried many times to do it myself, but I seem to be getting myself confused. So i decided to re read all the material for this section a few times and understood the principles. Below I have used the solutions given to us by Ivan.

Looping a Triangle

for (rows = "#"; rows.length < 8; rows += "#")

console.log(rows);

FizzBuzz

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

var output = "";

if (n % 3 == 0)

output += "Fizz";

if (n % 5 == 0)

output += "Buzz";

console.log(output || n);

}

Chess Board

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

1_ looping triangle
for (var i = “#”; i < “########”; i+="#") {
console.log(i);
}

2_FizzBuzz
for (var i = 0; i < 101; i++) {
if (i % 3 == 0 && i % 5 == 0) {
console.log(“FizzBuzz”);
continue;
};
if( i % 3 == 0){
console.log(“Fizz”);
continue;
};
if (i % 5 == 0) {
console.log(“Buzz”);
continue;
};
console.log(i)
}

3_ chess board

for (let i = 0; i < 8; i++) {
let oddLine=" # # # #";
let evenLine="# # # # ";
if (i % 2 == 0) console.log(evenLine);
else console.log(oddLine); }

Heya, can anybody input on why my code doesn’t work for Exercise 3 - Chessboard? Spaghetti code aside, the logical flow works, and the results are as desired for any character except the space - " " ! For some reason, the " " character doesn’t show up at the beginning of a new row. I can’t figure if it’s because of the < br > or the document.write command of something else. If I use an underscore or anyother character, I get the chessboard pattern as expected, but the blank space won’t show up for the life of it! :confused::face_with_raised_eyebrow:

var size=8;
var counter=1;

while(counter<=size)
{

if(counter % 2 == 0)
{ var lineLength1=1;
  while(lineLength1<=size)
  {

    if(lineLength1 % 2 == 0)
    {
     document.write(" ");
    }

    else
    {
     document.write("#");
    }

  lineLength1++;
  }
document.write("<br>");
}

else
{
  var lineLength2=1;
    while(lineLength2<=size)
    {

      if(lineLength2 % 2 == 0)
      {
       document.write("#");
      }

      else
      {
       document.write(" ");
      }

    lineLength2++;
    }
  document.write("<br>");
}

counter++;
}

Bit of a late answer here so I don’t know if you’re still unsure about this. The } (closing curly braces) are used to close the function or object so putting them anywhere after is fine. You don’t have to worry about spaces, tabs, or new lines because javascript ignores those.

Programmers usually put them in a new line indented just as far as the beginning of the function is indented for better readability, and right after the last value when defining an object.

I had the same issue. I think its because html ignores the first space in a new line. You can change the document.write into console.log and see if it shows up in the console to be sure.

1 Like

This was tough for me to figure out on my own so I did source this forum for ways to complete what I was working on. After exploring what was here I modified my own solutions.

  1. Triangle Loop

I used the simplest loop like in the textbook like so:

let number = #; while (number <= #######) { console.log(number); number = number + #;

It didn’t work because I didn’t use the .length function…

I do prefer this one line code solution to the triangle loop:

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

  1. Fizz Buzz

This one I was mostly able to figure out on my own.

let n = 0;
while (n <=99) {
  n = n + 1;
  let output = "";
  if (n % 3 == 0) output += "Fizz"
  if (n % 5 == 0) output += "Buzz"
  console.log(output || n);
}
  1. ChessBoard

This one I had issues with. All I sought to do was explore solutions and do my best to understand how they worked so that I can grasp what is going on. After looking I did realize how simple this code can be. Here are two of my favorite that I found easiest to understand:

var chess=8;
var board1="# # # #";
var board2=" # # # #";
for(i = 1; i<=chess; i+=2){
console.log(board2+"\n");
console.log(board1+"\n");
}

AND

for (let n = 1; n <= 8; n++) {
let output = "";
if (n % 2 == 0) output += "# # # #";
if (n % 2 == 1) output += " # # # #";
console.log(output);
}

Triangle Loop

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

FizzBuzz Loop

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

ChessBoard Loop

checkBDSize = 8;
checkb = "#";
space = " ";
boardLn = checkb;
boardLnCheck = true;
fill = false;
for(row = 0; row < checkBDSize; row++){
    for(var col = 0; col < checkBDSize; col++){
      if(fill){
        boardLn += checkb;
        fill = false;
      } else if(fill == false){
        boardLn += space;
        fill = true;
      }
      if (col == checkBDSize-1) {
        console.log(boardLn);
        if (boardLnCheck){
          boardLn = space;
          boardLnCheck = false;
          fill = true;
        } else {
          boardLn = checkb;
          boardLnCheck = true;
          fill = false;
        }
      }
    }
}