This is the solution:
for (let line = "#"; line.length < 8; line += "#")
console.log(line);
My question is : If line = "#", why can't line be used on the right hand side of the += operator like so:
for (let line = "#"; line.length < 8; line += line)
console.log(line);
Since you're adding line to itself each time, line will grow exponentially. Run the code here to take a look:
for (let line = "#"; line.length < 20; line += line) console.log(line)
By doing for (let line = "#"; line.length < 8; line += "#") console.log(line);
You ensure that line only increases by one "#" in each iteration.
Related
I'm new to programming and am curious so I thought I'd reach out.
I have tested myself with 2 outputs to the console, one being FizzBuzz and the other being a chessboard.
My question is why does my chessboard naturally (without "\n") print horizontally and FizzBuzz print out vertically even though they both use the same for loops?
Thanks, Luke.
FizzBuzz,
for(let i= 1; i<= 100; i++){
let message= "";
if(i %3 === 0 && i%5 === 0){
message= "FizzBuzz"
}else if(i % 3 === 0){
message = "Fizz";
}else if(i % 5 === 0){
message = "Buzz"
}
console.log(message || i);
};
Chessboard
let size= 8;
let board= '';
for (let x = 0; x < size; x++){
for (let y= 0; y < size; y++){
if((x+y) %2 == 0){
board += '#';
}else{
board += " ";
}
}
board += "\n"
}
console.log(board);
I think I have the answer.
(A) The code,
console.log("Fizz");
console.log("Buzz");
gives output
"Fizz"
"Buzz"
(B) But,
console.log("Fizz " + "Buzz");
gives output
"Fizz Buzz"
What you are doing with the FizzBuzz is similar to case (A) and in chessboard is similar to case (B). You are logging in every iteration of the for loop in case (A), but only once for every row in case (B).
Since you are new to programming, remember that each console.log("whatever"); logs "whatever" in a new line every time it is run.
So I'm making a loop that's supposed to print from 0-99 and it's supposed to make a new line after every 6th number like in the example below;
012345
678910
But right now it doesn't make a new line it just increases space between the "chunks" it's displaying. How do I get it to make a new line after every 6th number?
for (var i = 0; i < 100; i++) {
for (var j = 0; j < 6 && i <= 100; j++) {
document.body.innerHTML += i;
i++;
}
document.body.innerHTML += '\n';
i--;
}
A literal newline doesn't result in a visual newline in HTML:
foo
bar
You need <br> instead:
for (var i = 0; i < 100; i++) {
for (var j = 0; j < 6 && i <= 100; j++) {
document.body.innerHTML += i;
i++;
}
document.body.innerHTML += '<br>';
i--;
}
Or, I'd prefer to surround each block in a <div> - and you can increment the i only inside the inner loop to make the logic clearer:
for (var i = 0; i < 100;) {
const div = document.body.appendChild(document.createElement('div'));
for (var j = 0; j < 6 && i <= 100; j++, i++) {
div.textContent += i;
}
}
You could use a modulus to insert a br every sixth item - save you doing loops inside loops:
for (var i = 0; i < 100; i++) {
document.body.innerHTML += i;
if ((i + 1) % 6 === 0) { // using i plus one as you start at 0
document.body.innerHTML += '<br>';
}
}
I am answering
supposed to print from 0-99 and supposed to make a new line after every 6th number
We need a PRE to not use a <br>
document.getElementById("res").innerHTML =
Array.from(Array(100).keys())
.map(i => `${i.toString().padStart(3," ")}${(i + 1) % 6 === 0 ? '\n' : ''}`)
.join("");
<pre id="res"></pre>
I have this loop problem, I really don't understand why my code doesn't work, I've even draw this on paper and for my logic it looks good but it's not working, please help me.
function drawTree(h) {
for(var i=0; i<=h; i++){
var star = '';
for(var k=0; k<=1; k++){
star += " ";
};
for(var j=0; j<=i; j++) {
star += "*";
};
};
console.log(star);
};
drawTree(5);
See comments in the code for changes.
function drawTree(h) {
for(var i=0; i<=h; i++){
var star = '';
//Changed to start high then decrease
for(var k = 1; k <= h - i; k++){
//shortened to one space
star += " ";
};
for(var j=0; j<=i; j++) {
//Added space so there is an odd number
//of symbols and the star above fits
//the space
star += " *";
};
//Moved into the loop
console.log(star);
};
};
drawTree(5);
Note that the code can be substantially shortened using String.prototype.repeat:
function drawTree(h) {
for (var i = 0; i <= h; i++){
console.log(" ".repeat(h - i) + " *".repeat(i + 1));
};
};
drawTree(5);
Also note that your example produces a base line with six stars for a call of drawTree(5). I am unsure whether that is intended. The code above reproduces said behavior, editing it to show a line less should not be too hard.
function drawTree(h) {
for (var i = 0; i < h; i++) {
var star = '';
var space = (h - i);
if (i == 0) {
star += ' '.repeat(space + 1) + '\n';
}
star += ' '.repeat(space + 1);
var zero = 2 * i + 1;
star += '*'.repeat(zero);
console.log(star);
}
}
drawTree(5);
You’re re-setting it each line, but printing it only at the end.
Move console.log(star); to the end of the first loop.
Just for fun:
const tree = ({height: h = 5, stumpHeight: sh = 2, branchChar: bc = '*', emptyChar: ec = ' ', stumpChar: sc = '#'} = {}) => [
... Array .from ({length: h}, (_, n) => ec .repeat (h - n - 1) + bc.repeat (2 * n + 1) + ec .repeat (h - n - 1)),
... Array .from ({length: sh}, () => ec .repeat (h - 1) + sc + ec .repeat (h - 1)),
] .join ('\n')
console .log (tree ())
console .log (tree ({height: 6, emptyChar: '_'}))
console .log (tree ({height: 12, stumpHeight: 3, stumpChar: '#'}))
console .log (tree ({branchChar: '#'}))
.as-console-wrapper {max-height: 100% !important; top: 0}
Because, you know, that's how all those JS 101 instructors expect it to be coded.
function drawTree(n) {
let tag = "#";
for (let i = 0, j = "#"; i < n; i++) {
console.log(tag);
tag = tag + j;
}
}
drawTree(10);
You have to place the console.log statement inside first for loop. That should give a half tree.
If you want correct tree, then pre-pend spaces before star.
Calculate the center of the number of rows and add spaces before it.
Hope this not an assignment problem.
function drawTree(h) {
for(var i=0; i<=h; i++){
var star = '';
for(var k=0; k<=1; k++){
star += " ";
};
for(var j=0; j<=i; j++) {
star += "*";
};
console.log(star);
};
};
drawTree(5);
I'm trying to build a triangle using nested loops.
var line, triangle;
line = triangle = "";
for (var row = 1; row <= 7; row++) {
for (var x = 0; x < row; x++) {
line += "#";
}
triangle += line + "\n";
}
console.log(triangle);
I expected that each row is more than the last by only one "#" like this:
But this is the result I got:
The reason your code does it is you are updating line on each iteration and you keep appending to it. If you want to do the nested loops, than you need to reset the variable line each time you are in the outer loop.
var line, triangle;
line = triangle = "";
for (var row = 1; row <= 7; row++) {
line =""
for (var x = 0; x < row; x++) {
line += "#";
}
triangle += line + "\n";
}
console.log(triangle);
Or you can keep what you have and dump the inner loop and every iteration you just add one character to the line.
var line, triangle;
line = triangle = "";
for (var row = 1; row <= 7; row++) {
line += "#";
triangle += line + "\n";
}
console.log(triangle);
You need to empty your line before each nested iteration. Without this you have one line and every time concatenate new items to it. Also you can leave the line variable and just use the triangle.
var triangle = '';
for (var row = 1; row <= 7; row++) {
for (var x = 0; x < row; x++) {
triangle += "#";
}
triangle += "\n";
}
console.log(triangle);
You can also try this solution with String#repeat
var triangle = '';
for (var row = 1; row <= 7; row++) {
triangle += '#'.repeat(row) + '\n';
}
console.log(triangle);
function triangle(num) {
for(let i = '#'; i.length < num; i+='#') {
console.log(i)
}
}
Try code below:
function generatePyramid() {
var totalNumberofRows = 7;
var output="";
for (var i = 1; i <= totalNumberofRows; i++) {
for (var j = 1; j <= i; j++) {
output+= "# ";
}
print(output);
output="";
}
}
generatePyramid();
How it works: http://rextester.com/ULY85622
EDIT: Fixed it by just adding one line - you need to reinitialize the variable "line" after each row iteration
var line, triangle;
line = triangle = "";
for (var row = 1; row <= 7; row++) {
line="";
for (var x = 0; x < row; x++) {
line += "#";
}
triangle += line + "\n";
}
console.log(triangle);
You need to reset line after each loop because it is accumulating all # on each cycle:
var line, triangle;
line = triangle = "";
for (var row = 1; row <= 7; row++) {
line = "" // Add this line
for (var x = 0; x < row; x++) {
line += "#";
}
triangle += line + "\n";
}
console.log(triangle);
Your code is incorrect because line follows the following steps on each cycle:
row 1: line starts as '' and ends as # (Adds #)
row 2: line starts as # and ends as ### (Adds ##)
row 3: line starts as ### and ends as ###### (Adds ###)
row 4: line starts as ###### and ends as ########## (Adds ####)
row 5: line starts as ########## and ends as ############### (Adds #####)
row 6: line starts as ############### and ends as ##################### (Adds ######)
row 7: line starts as ##################### and ends as ############################ (Adds #######)
I'm attempting to make a function that builds a checker board however I can't get my second conditional statement to execute and create a new line.
function grid(size) {
var board = "";
for (i = 0; i <= (size * size); i++) {
if (i % 2 === 0) {
board += ' ';
} else if (i % size === 0) {
board += "\n";
} else {
board += '#';
}
}
console.log(board);
}
grid(8);
It appears the else if statement is not executing because I've tried changing the '\n' and condition to other things but nothing is printed. This question is from Eloquent Javascript and the given solution is this:
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);
I'm not sure why the second one works but mine doesn't.
Let´s analyse your code:
if(i % size === 0)
This means, when i is equal to 0 or is a multiple of size. In your case, size is 8.
So for your if to trigger, i should be 0,8,16,32....
In all this cases, it will never fire because when i is 0,8,16,32... i % 2 is 0, so it will run the first if instead and never the second one. You should inverse the order of the ifs or run both
i % 2 will always execute instead of i % (8 * 8). You should swap their order or remove the else from the second if.