I've recently completed a challenge in Marjin Haverbeke's book, "Eloquent Javascript, Second Edition".
One had to create this console output using a for loop:
#
##
###
####
#####
######
#######
The answer is this:
for (var i = '#'; i.length < 8; i += '#') {
console.log(i);
}
What I would like to know is why the first line is not two hashes ('##') as surely the updating section of the loop (i += '#') adds '#' to i (already = to '#'), therefor meaning that the first iteration of the loop should surely output '##'?
Perhaps I need a lesson on how this loop really works.
Yours truly,
still seemingly JS newbie.
for (init(); condition(); update()) {
body();
}
is equivalent to
init();
while (condition()) {
body();
update();
}
Thus, the first time i += '#' runs is only after the first console.log(i) (when i was just '#').
#Callum you should first check how for loop works.
if you have written .
for (var i = '#'; i.length < 8; i += '#') {
console.log(i);
}
so what happen in this loop is this .
1 ) first var i ='#' initiallize
then condition
2) i.length < 8
then it goes to executed the statement
3) console.log(i);
4) then increment
i += '#'
then from step 2 to 4
this is what for loops algorithm works
it is just like post increment. The order of execution is:
--> initialisation
--> check condition
--> execute body
--> increment value
so first it would print the value then increment it.
This would give ## in first row:
for (var i = '#'; i += '#',i.length < 8; ) {
console.log(i);
}
Related
I had to check the solution for the first exercise in the book, and as I understand it, it's almost identical to my answer.
The exercise:
Write a loop that makes seven calls to console.log to output the following triangle:
the solution, that is given by the book:
for (let line = "#"; line.length < 8; line += "#")
console.log(line);
and my solution:
for (let hash = '#'; hash.length <= 7; hash++) {
console.log(hash);
};
My question is, why my loop doesn't loop? As it is explained in the book:
For counter += 1 and counter -= 1, there are even shorter equivalents: counter++ and counter--.
So by this logic, it should work.
You are trying to increment a character. This doesn't concatenate to the character as you want it to and instead increases the ASCII value of the character.
Modify your code a bit:
for (let hash = "#"; hash.length <= 7; hash += "#") {
console.log(hash);
};
hash should be a string so that you can concatenate to it; furthermore, you shouldn't try to increment hash but rather concatenate to it on every iteration of the loop.
I basically just want to print numbers a list of numbers a skip multiples of 3. I got it to work but the initial way i tried it did not work and i do not understand why, just need someone to please explain why it doesn't work and goes into an infinite loop.
This is the problem, why does it go into an infinite loop? I am clearly missing a key concept about code, if someone could help thanks.
var i = 0;
while (i <= 10) {
if (i % 3 == 0) {
continue;
}
document.write( i + "</br>");
i++;
}
I know you can do it this way.
while (i <= 10)
{
if (i % 3 != 0) {
document.write("Number is " + i + "<br />");
}
i++
}
If we ignore the code producing the output and look only at the code checking and modifying i, it might become a little more clear why it's not working. It also helps to format our code for extra clarity.
var i = 0;
while (i <= 10) {
if (i % 3 == 0) {
continue;
}
i++;
}
Start with i = 0.
i <= 10 is true. Enter the loop.
i % 3 == 0 is true. Enter the if block.
continue;. Go straight to the top of the while loop again. Do not pass i++;. Do not collect 1.
Lather. Rinse. Repeat (infinitely).
continue jumps to the next iteration and doesnt complete the rest of your code in the while. So i is not being incremented but rather staying as 0 becuase you wrote continue before incrementing the i. so therefore it is in an endless loop, it is always less than 10
I currently have this small script that outputs a value after each iteration of a while loop:
var i = 0;
var number = "";
while (i < 10) {
number += console.log(i);
i++;
}
Which creates this output:
0
1
2
3
4
5
6
7
8
9
However, I am testing some API calls and using the while loop in JavaScript to see if I can send values consistently, so my values are coming from the script below:
var i = 0;
var number = "";
while (i < 10) {
number += (i);
i++;
}
I do not need console.log() because I do not need the output in the terminal. My issue is when looking at the output on the receiving end when using the API, it looks something like this:
0
01
012
0123
01234
012345
0123456
01234567
012345678
0123456789
The API calls are in the while loop as well, I did not include them because I feel this is a JavaScript syntax related issue. So what will happen is that the while loop begins, number is iterated, that value is sent to a website using an API call, and the the while loop begins again. Something like the code below:
var i = 0;
var number = "";
while (i < 10) {
number += (i);
API_Send(number)
i++;
}
What can I do to so that the output of each iteration is its own separate variable similar to the output using console.log(), so first iteration is 0, second iteration is 1, and so on.
I feel this is something that would be necessary when outputting values to be used by a function. So perhaps it is best to create a function that has a while loop outputting integer values?
The problem is that you have declared number as string, don't do that just assign 0 to number variable.
Because of string variable javascript is concatenating the numbers.
Change as following:
var i = 0;
var number = 0;
while (i < 10) {
number += (i);
console.log(number)
i++;
}
I just have a question about some while loop logic.
So, when you write a loop that displays a string of numbers to a document and say that while the loop is <= (less than or equal to) say, 5, and you tell the loop to add 1 each time this is true, wouldn't that mean that: while the loop is equal to 5 that it would add one to 5 too? It doesn't, but I messed up on some code when I was practicing and noticed that when it is equal to five it does not add one, but I thought it would...
console.log('2nd Loop:');
text = '';
// loop:
i = 1;
while (i <= 5) {
text += i + ' ';
i += 1
}
console.log(text); // Should print `1 2 3 4 5 `.
the reason your text doesn't display a 6 isn't because i isn't incremented. It's because the text gets added onto before it's incremented.
In other words when executing on that 5th loop, the text would add on 5, and then it would increment i, and then it would check the loop again, which would no longer be valid and therefore 6 is never printed.
In memory, it adds one. It doesn't add it to the text though.
Since you're incrementing the value after assigning it and then the loop condition fails, it doesn't get to the part where you concatenate the string.
It does. Just output i and you'll see it's 6. text never gets the 6 because of when you increment i.
console.log('2nd Loop:');
text = '';
// loop:
i = 1;
while (i <= 5) {
text += i + ' ';
i += 1
}
console.log(text,i); // Should print `1 2 3 4 5 `.
b/c you +1 after you add i to text, all you need to do is switch the two line order.
EDIT
if you want it start with one just change your i to 0 to start with.
i = 1
console.log('2nd Loop:');
text = '';
i = 0;
while (i <= 5) {
i += 1
text += i + ' ';
}
console.log(text);
I am working on Chapter 2 Exercise 3 in Eloquent Javascript, Chess Board. I am having an issue understanding one part and hoping someone would be able to provide a little enlightenment.
My Code:
var size = 7;
var board = "";
for(var i = 0; i <= size; i++){
for(var j = 0; j <= size; j++){
if((i + j) % 2 === 0){
board += " ";
} else {
board += "#";
}
}
board += "\n";
}
console.log(board);
The issue that I am having is with the condition of the "if" statement.
if((i + j) % 2 === 0)
I am not understanding why I need to add i and j together. Isn't the first "for" loop that contains the i variable constructing the row and how many rows? Where as, the second "for" loop that contains the j variable is creating the content within each row?
The addition of i and j is to create the checkerboard pattern. If the sum is even, a white square (" ") is printed; otherwise it is black ("#").
Also, your conditional statement contains a triple equals sign instead of the desired ==.
It is creating a checker board pattern so the rows are off by one on each iteration. If the row was not used, it would create stripes.
Currently with i + j % 2
# # # #
# # # # #
# # # #
# # # # #
If it were just j % 2
# # # #
# # # #
# # # #
# # # #
If it were just i % 2
.
########
########
########
I think I'am a little late to answer but will do so anyway.
Its because your want to create a pattern that looks like something like this.
"# # # #"
" # # # "
therefor you are going to add the variable "i" that is used to count from your outer loop and the variable "j" from your inner loop that is used to count, to decide with the help of an if/else statement to output either a "#" or " "(space). Also not that your first outer loop will stay at 0 until the vairable "j" in your inner loop is equal to "size". Meaning that one the first run (i+j) is = to 0+1, 0+2, 0+3, 0+4, 0+5, 0+6, 0+7. Once the inner loop is done the outer loop adds a "\n" and the procces is repeated but this time your outer loop vairable that is used to count changes from 0 to 1 and your inner loop variable that is used to count resets to 0 and your expression (i+j) is now equal to 1+0, 1+2, 1+3 ect
var size = 7;
var board = "";
for(var i = 0; i <= size; i++){ /*This will remain 0 the first run until the inner loop is completed then it will add the "\n" at the end*/
for(var j = 0; j <= size; j++){/* the variable j here will keep adding 1 to itslef until it j is equal to size*/
if((i + j) % 2 === 0){/* here it will add both i+j then divide it by 2 in order to see if is an even number or not.
remember it will look something like the this first run 0+1, 0+2, 0+3 ect.*/
board += " ";// here if the number is even it will output a (space)
} else {
board += "#";// here if the number is not even it adds "#"
} // finally this inner loop gets repeated until your vairable "j" is equal to "size"
}
board += "\n";/* then the outer loop adds a new line and your vairable "i"
becomes 1 and this whole loop gets reapeated until "i" is equal to "size"*/
}
console.log(board);
hope this helped excuse my grammar, my english is not that good greetings from Mexico City