Chapter 2 Exercises

First of all… as a complete newbie to coding, I found these programming exercises challenging.

If anyone could help explain exercise 3. Chessboard (see questions below), I would appreciate it!

//Exercise 1. Triangle

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

//Exercise 2. Fizzbuzz

for(let num = 1; num <=100; num++)

if(num % 3 == 0 && num % 5 == 0) {
console.log(“FizzBuzz”)
}

else if(num % 3 === 0) {
console.log(“Fizz”)
}

else if(num % 5 === 0) {
console.log(“Buzz”)
}
else {
console.log(num)
}

// Exercise 3. 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);

Questions\ regarding ‘Chessboard’ I couldn’t find answers to…

A. Why is there a \n at the end of the code? I don’t understand what role this new line is playing and how it fits in with the rest of the code above it.

B. Please help explain: board += " ";
How is the above ensuring that a space is filled in across the row or down the column all the way until the end of the grid?

Thankyou in advance!

Also how does one write their code in these answers so that the text appears in the grey shaded box?

hastags

// variables
	var a = 0;
	var hastag = "#";
	// while loop 
	while(a<7){
	document.write(hastag + "<br>");
	a++
	hastag += "#";
	}

fizzbuzz

	var i = 1;
	while(i<101){
	
		if (i % 3 == 0 && i % 5 == 0) document.write("FizzBuzz ");
			else if(i % 3 == 0) document.write("Buzz ");
				else if(i % 5 == 0) document.write("Fizz ");
					else document.write(i + " ");
	i++
	}

i think this chessboard is not what the teacher wanted to see but i found a working solution…

var magicnumber = 8;
var col1 = "# &nbsp;";
var col2 = "&nbsp; #"; 
var grid = magicnumber / 2;

// a loopie!
for (i=0; i<grid; i++) {
	document.write(col1.repeat(grid) + "<br>" + col2.repeat(grid) + "<br>");
}
1 Like

hey Denci, I had the very same problem. Kind of demotivating also, because the answer didn’t even come close to what I was creating in my own code. Not even a bit close. It was totally different than I was thinking. I found it to be a very great leap in thinking for a noob like myself.

Hi Philippa,

select the text end click </> in the top menu of the wsiwyg esditor!

1 Like

Hi Philippa,

where did you find that code? :slight_smile:
/n means begin a new line. so if you want to do this:
# # #
and then
  # # #
those are two lines. But if you want to wright it on one single ine of code you have to make an enter. Someone correct me if i’m wrong but i think that is what your question is referring to. I’m also learning!

+= can can be found in the lesson from ivan named while loop. i suggest you watch that again to get an better idea!

for(a=1;a<=100;a++){
if(a%3==0 && a%5==0){console.log(“BuzzFizz”)}
else if(a%3==0){console.log(“Fizz”)}
else if(a%5==0){console.log(“Buzz”)}
else{console.log(a)}}
i just did it logically by what ws taught till that time

Thank you for your answers @huupie

The code I provided in my answer were solutions provided from the Eloquent Javascript book (except the Fizzbuzz one, which I seemed to miraculously work out).

Here are my solutions, as I’m already a programmer I’ve tried to comment the code to help newbie to understand it better.
Not only for the instruction I’ve used but I’ve also tried to explain the logic behind and how my mind has worked to find out the solution.

@Philippa the first solution you have found is really smart! may be not easily understandable by a beginner but it illustrate perfectly the power or loops and programming languages in general. With just 1 or 2 lines of code you can do lots of things!

by the way here is my code, less smart but I hope more didactic.

Hope this will help :smile:

<script>
	//TRIANGLE
	//I declared a string variable to store the whole text 
	//to print out on the console all toghether at the end.

	let triangle = "";

	//Then I needt to print 7 rows
	//so I created a loop to iterate for 7 rows (from rowIndex = 1 until rowIndex stay lower or equal to 7)
	//this can also be done like: for (let rowIndex = 0; rowIndex<7; rowIndex++) as you prefer

	for (let rowIndex=1; rowIndex<=7; rowIndex++) {

		//for each row I need to print as many # as the current row number
		//so, for example, if I'm on the 3rd line I need to print ###
		//therefore another loop is needed to add 1 # at the string as many times as the current row number

		for (let colIndex = 1; colIndex <= rowIndex; colIndex++) {
			triangle += "#"
		}

		//once exited this loop means that a row has been completed
		//and I need to add a New line caracter to end the line

		triangle +="\n";
	}

	//once exited this loop the whoole triangle string has been prepared
	//and need just to be printed out to the console.

	console.log(triangle);
	
	//FIZZBUZZ
	//as in the previous exercise I store the whole string in a variable
	//and print it out just at the end.

	let fizzbuzz = "";

	//as it's needed to print out numbers from 1 to 100
	//I created a loop exactly from 1 to 100

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

		//To check if the number is divisible by 3, 5 or both we can use the module (%) operator.
		//if the result of the module is 0 it means that the number is divisible
		//Here the order of conditions is very important.
		//We need to check first if it's divisible by both 3 and 5
		//instead than checking first just 3 or 5 because this will lead to a bug
		//writing "fizz" or "buzz" (depending on the order) instead of "fizzbuzz" on number like 15 for example.
		//Try changing the order of the conditions to check the results.
		//As in the example before a \n is added at the end of each line to go to a new line.

		if (currentNumber % 3 == 0 && currentNumber % 5 == 0) {

			//it's divisible both by 3 and 5

			fizzbuzz += "fizzbuzz\n";
		} else if (currentNumber % 3 == 0) {

			//it's divisible by 3 and obviously not by 5 because instead it would have entered the previous condition

			fizzbuzz += "fizz\n";
		} else if (currentNumber % 5 == 0) {

			//it's divisble by 5 and obviously not by 3 because instead it would have entered the previous conditions

			fizzbuzz += "buzz\n";
		} else {
			
			//if no other condition matched it's not divisible neither by 3 nor by 5
			
			fizzbuzz += currentNumber + "\n";
		}
	}

	//once completed the loop we can print out the whole string

	console.log(fizzbuzz);

	//CHESSBOARD
	//To solve this exercise I used a mix of the previous 2.
	//we need 2 nested loops one for iterating on each row and one on each colum
	//and a module to determine if in the current position I'm I should write a ' ' or a '#'.
	
	//Looking at the printed result we are asked for, I can see 2 possible different printed pattern for a row.
	//The odds rows (1, 3, 5...) have # on the even positons (column 2, 4...)
	//The even rows (2, 4, 6...) have # on the odds position (column 1, 3...)

	//as in the previous example I defined a string variable to contain the whoole string to print out at the end.

	let chessboard = "";

	//I defined also a size variable to make thi exemple valid for any chessboard size

	let size = 8;

	//here we are iterating for each row

	for (let rowIndex = 1; rowIndex <= size; rowIndex++) {

		//here I define 2 variables to store wich character to use for Odd and Even columns
		//it has to change for each row as described in the 2 pattern identified before.
		//so it changes depending on if the current rowIndex is even (rowIndex % 2 == 0) or odd

		let oddChar = " ";
		let evenChar = "#"
		if (rowIndex % 2 == 0) {
			oddChar = "#";
			evenChar = " "
		}

		//for each row we need to loop also for each colums

		for (let colIndex = 1; colIndex <= size; colIndex++) {

			//here we need to determine if we are in a even column or in an odd one
			//to add the specific character to the string.

			if (colIndex % 2 == 0) {
				chessboard += evenChar;
			} else {
				chessboard += oddChar;
			}
		}

		//as in the previous execises at the end of each row we need to ad a new line break

		chessboard += "\n";
	}

	//once the last loop has ended we are ready to print out the string

	console.log(chessboard);
</script>
4 Likes

TRIANGLE LOOP
let numRows = 7;

let rowIcon = “#”;

for(let i = 0; i < numRows; i++)
{

console.log(rowIcon);
rowIcon+= "#";

}

FIZZBUZZ

let maxCount = 100;
for(let i = 1; i <= maxCount; 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

let height = prompt("Enter height of board: ");
let width = prompt("Enter width of board: ");

let gridString = “”;
let temp1 = “”;
let temp2 = “”;

for(let i = 1; i <= width; i++)
{
if(i%2 != 0)
{
temp1 += " ";
temp2 += “#”;
}

else
{
  temp1 += "#";
  temp2 += " ";
}

}

for(let i = 1; i <= height; i++)
{

if(i%2 != 0)
  gridString += temp1;

else {
  gridString += temp2;
}

gridString+="\n";

}

console.log(gridString);

Here are my solutions:
//looping triangle
hash = “#”;
for(x=0;x<7;x++)
{console.log(hash);
hash += “#”;
}

//fizz-buzz 1

for(y=1;y<101;y++){
if(y%3==0){console.log(“fizz”)}
else if (y%5==0&&y%3!=0) {console.log(“buzz”)
}else{console.log(y)}
}

//fizbuzz 2

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

//cecker-board

let size = 8
let rowEven = “”
let rowOdd = “”
for(x=size ; x>0 ; x–){
if(x%2==0){
rowEven = rowEven + " ";
}
else{
rowEven = rowEven + “#”;
}
}
for(x=size ; x>0 ; x–){
if(x%2==0){
rowOdd = rowOdd + “#”;
}
else{
rowOdd = rowOdd + " ";
}
}

for(x=size ; x>0 ; x–){
if(x%2==0){
console.log(rowEven);
}
else{
console.log(rowOdd);
}
}

//checker board v2
let size2 = 8;

for(x=size2;x>0;x–){
let str = “”;
if(x%2==0){
for(y=size2;y>0;y–){
if(y%2==0){
str= str + " ";
}
else{
str = str + “#”;
}

  }
console.log(str);
str = "";
}
else{
  for(y=size2;y>0;y--){
    if(y%2==0){
      str= str + "#";
    }
    else{
        str = str + " ";
    }

  }
  console.log(str);
  str = "";
}

}

Triangle loop

let num_rows = 7;

  for(let row=0; row < num_rows; row++){

    let toPrint = "#";
    // First time it skips bcs column and row = 0
    for(let column = 0; column < row; column++){
      toPrint += "#";
    }
    document.write(toPrint+"<br>");
    
  }

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

    if(row % 3 == 0 && row % 5 == 0){
      console.log("FizzBuzz");
    } else if (row % 3 == 0){
      console.log("Fizz");
    } else if (row % 5 == 0){
      console.log("Buzz");
    } else {
      console.log(row);
    }

  }

Chessboard
size = 8;

  for(let rowNum=1; rowNum <= size ; rowNum++) {

    let toPrint = "";

    for(let colNum=1; colNum <= size; colNum++){

      if(colNum % 2 == 0){

        if(rowNum % 2 == 0){ // col 2 row 2
          toPrint += " ";
        } else { // col 2 row 1
          toPrint += "#";
        }

      }else{

        if(rowNum % 2 == 0){ // col 1 row 2
          toPrint += "#";
        } else { // col 1 row 1
          toPrint += " ";
        }

      }

    }
    console.log(toPrint);
    //console.log(rowNum);
  }

Thank you so much @iLFusta for taking the time to answer. Your explanation behind the code was extremely helpful to develop my understanding of the solutions.

2 Likes

decided not to use new line character?

nice simplicity, i might be here for a hot minute. jeje

**Triangle...**
      for (let row = 0; row < 7; row++) {
        var hashes = "#";
        for (let col = 0; col < row; col++) {
          hashes = hashes+"#";
        }
        console.log(hashes);
      }

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

**Checker Board...**
        var width = 8;
        var height = 8;
        var board = "";
        var square = "#";
        var newLineCharacter = 0;

        for (let i = 0; i < width * height; i++) {
          square = switchSquare(square);
          board = board + square;
          if((board.length - newLineCharacter) % width == 0){
            board = board + "\n";
            newLineCharacter = board.length;
            square = switchSquare(square);
          }
        }
        console.log(board);

        function switchSquare(square) {
          if (square == "#"){
            square = " ";
          } else {
            square = "#";
          }
          return square;
        }
    </script>

Looping A Triangle

    var row = 7;
            
    for(var i = 0; i < row; i++){
        for( var j = 0; j <= i; j++){
            document.write("#");
        }
        document.write("<br>");
    }

FizzBuzz

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

ChessBoard

    var size = 8;  
    var string = " ";
  
    for(var i = 2; i < size**2; i++){
        if(i%2 == 0)
            string = string + "#";
        else
            string = string + " ";
        if(i%(size+1) == 0)
            string = string + "\n";           
    }
    console.log(string);

FizzBuzz

//write code here
var fizz = "Fizz";
var buzz = "Buzz";

for(var cnt = 1; cnt < 101; cnt++)
{
  if(cnt%5 == 0 && cnt%3 == 0){
    console.log(fizz+buzz);
  }
  else if(cnt%5 == 0 && cnt%3 != 0){
    console.log(buzz);
  }
  else if(cnt%3 == 0){
    console.log(fizz);
  }
  else{
    console.log(cnt);
  }
}

Chess Board

var num_rows = 8;
for(var row = 1; row <= num_rows; row++)
{
  var hash1 = "";
  for(var column =1; column<=num_rows; column++)
  {
if(row%2 == 0)
{
   hash1 += " #";
}
else
{
  hash1 += "# ";
}
}
 console.log(hash1 + "\n");
}

Triangle

mr = 7
sym="#"
for (r=0; r < mr; r++) {
for (c=0; c < r; c+=mr) {sym+="#";}
document.write(sym + “
”);}

Chess
size = 8;
toPrint = “”;
for (row = 0; row < size; row++) {
for (col = 0; col < size; col++) {
if ((row + col) % 2 == 0) {
toPrint += “&nbsp”;
} else {
toPrint += “#”;
}
}
toPrint += “br>”;
}
document.write(toPrint + “br>”);