Considering this code:
var x = 3;
var i = 0;
while (i < 3) {
x += 1;
i += 1;
}
println(x);
Why would the output be 6? Can someone break it down for me?
I understand that x will continue adding 1 to it's value, but why does the i<3 limit it to 6?
The answer will be 6 because your initial value of X is 3.
You have only 3 iterations in your while loop.
i = 0 => x +1 = 4
i = 1 => x + 1 = 5
i = 2 => x + 1 = 6
i = 3 => exit loop
I will explain it step by step
while loop will take values, while i is smaller than 3 right.
X starts as 3 and i starts as 0.
While checks if i < 3. (it is 0 for now )
(x+=1 means x = x + 1 (same for i ))
i was 0, so while loop will start working.
x will become 4 and i will become 1.
second run: i is 1 still lower than 3 so while loop will keep working.
x will become 5 and i will become 2
i is still lower than 3 so while loop will keep working
x will become 6 and i will become 3
now i is equal to 3 so no longer lower than 3. While loop will stop working and you will get the outputs.
But if console.log (x) was in the while loop. You will get all the x results.
The output would be:
4
5
6
So, if your question is why am I getting only 6 as an output? It is because your function comes after the while loop.
Before entering into the loop: x=3, i=0 (i is less than 3, so the condition is true)
After the first step: x=4, i=1 (i is less than 3, so the condition is true)
After the second step: x=5, i=2 (i is less than 3, so the condition is true)
After the third step: x=6, i=3 (i is not less than 3, so the condition is false)
Because the condition is false, it is exited from the loop and the value of x is printed in the output.
Also, println() is not defined in JavaScript. We can use console.log().
The code of
var x = 3;
var i = 0;
while (i < 3) {
x += 1;
i += 1;
}
increments x and i repeatedly. Initially, i is 0, which is important, as its incrementation's result determines whether the loop should continue. Since the loop criteria is that i < 3 is (still) true, starting from 0 and adding 1 to the value of i, your loop's block will be executed 3 times (it's executed for i=0, then it's executed for i=1 and then it's executed for i=2 and finally, for i=3 it's not executed, because the condition of i < 3 is no longer true when i=3).
Since the loop block is executed 3 times and both i and x is incremented by 1 at each execution, their value increases by the same value during the process. Since i was increased by 1 a total of three times, its value was changed from 0 to 3 (0 + 1 + 1 + 1 = 3). Since the initial value of x was 3, it changed from 3 to 6 (3 + 1 + 1 + 1 = 6).
Related
Good afternoon, please explain why, when waiting for 3, 4 is output to the console.
let x = 1;
console.log (x++ + ++x) // 4
At first, I thought that the priority of operations, but then why in such an example outputs 8, and not 6 for example?
let x = 1;
console.log (x++ + ++x + ++x) // 8
Sorry, if this question is duplicated, but I can't find any about this question.
For the first example:
let x = 1;
console.log (x++ + ++x) // 4
x++ returns the value of x (1) and increments it afterward. x is now 2. (This is postfix increment.)
++x increments the value of x and returns it, which is 3 (2 + 1). (This is prefix increment.)
1 + 3 = 4
See Increment Operator.
x++ or x-- is first use then update.
++x or --x is first update then use.
update means update the value of the variable x.
I'm having a hard time with this problem here:
Write a function named sumEvery5th that accepts a non-negative integer n and returns the sum of the integers divisible by 5 from 1 to n, including n itself. Use a for loop.
This is what I have so far:
var sumEvery5th = function(n){
let sum = 0;
for(let i = 1; n % 5 == 0; i++){
sum+ i
};
return sum;
}
I feel like I'm really close. Thanks for the help in advance.
You can start your loop at 5, since 1, 2... are not divisible by 5. And instead of i++, you can directly go 5 by 5, until i is greater than n:
var sumEvery5th = function(n) {
let sum = 0;
for (let i = 5; i <= n; i += 5) {
sum += i;
};
return sum;
}
console.log(sumEvery5th(10)); // 5 + 10 = 15
console.log(sumEvery5th(18)); // 5 + 10 + 15 = 30
First I think you should understand how a for loop works.
var sumEvery5th = function(n){
let sum = 0;
for(let i = 1; n % 5 == 0; i++){
sum+ i
};
return sum;
}
What you are doing, step by step, is:
Declaring a variable i with value 1.
Dividing n by 5 and taking the remainder value and comparing it with 0. In case it's true, you are skipping the code block inside the for and moving towards the return sum; line.
(In case you haven't skipped the code block in step 2) Run the code block with the new i value.
(In case you haven't skipped the code block in step 2) Incrementing the i value.
Go back to step 2.
Usually your for condition will depend in the variable declared in step 1. What you want to do is run the for code block n times.
For that, you need to change your condition from n % 5 == 0 to i <= n. This will make sure to run the code block while your i is less or equal than n, starting with a value of 1.
Now, inside your code block you add your divisible by 5 logic, checking against i value.
for(let i = 1; i <= n; i++){
if (i%5 == 0) sum += i;
};
Now let's say I called sumEvery5th(5).
Declare a variable i with value 1.
Check if i (1) is less than or equal n (5).
Go inside the code block.
Check if i%5 is 0.
It's not.
Increment i, now i = 2.
Check if i (2) is less than or equal n (5).
...And so on, until i = 6, and in that case the code block is skipped and the program will continue its course.
Ps.: There are ways to improve the performance of this algorithm, but now that you understand your for loop a bit better I'll leave it to you :)
var sumEvery5th = function(n){
let sum = 0;
for(let i = 1; i <= n; i++){
if (i % 5 === 0) {
sum += i;
}
}
return sum;
}
Since i += i is an abbreviation for i = i + i, the following code
for (var i = 0; i<=10; i++) {
console.log(i += i) }
should output:
1. 0, because 0 += 0 + 0 (i = 0)
2. 2, because 0 += 1 + 1 (i = 2)
3. 6, because 2 += 2 + 2 (i = 6)
4. 12, because 6 += 3 + 3 (i = 12)
However, although the console does output the values of 1. - 3., namely, 0, 2, and 6, correctly, the value that I get for 4., which is 14, is not the value that I predicted (the lines 1. - 4. above were typed out before the for-loop was executed) the for-loop would output (=12).
What am I interpreting wrong here?
The code itself is evidently uninteresting, but nonetheless I am curious why it works the way it does.
So basically, you are adding one then double the number in each iteration, starting with 0.
Then you should get: 0, 2, 6, 14. I think your math, not code, is wrong here.
Recall that for loops have four parts: Initialiation, Test, Body, and Increment.
...and they work like this:
Initialization
Test, jump to after loop if test is false*
Body
Increment
Go to step 2
So, here's the way that loop works:
(Initialization) i = 0
(Test) Since 0 is <= 10, keep going
(Body):
Evaluate i += i: Since i is currently 0, i = 0 + 0 is i = 0.
Log that
(Increment) Evaluate i++. Since i is 0, it becomes 1
(Test) Since 1 is <= 10, keep going
(Body):
Evaluate i += i: Since i is currently 1, i = 1 + 1 is i = 2
Log that
(Increment) Evaluate i++. Since i is 2, it becomes 3
(Test) Since 3 is <= 10, keep going
(Body):
Evaluate i += i: Since i is currently 3, i = 3 + 3 is i = 6
Log that
(Increment) Evaluate i++. Since i is 6, it becomes 7
(Test) Since 7 is <= 10, keep going
(Body):
Evaluate i += i: Since i is currently 7, i = 7 + 7 is i = 14
Log that
(Test) Since 14 is not <= 10, stop
* "Test, jump to after loop if test is false" Technically, not just false, but anything falsey, which is 0, null, undefined, NaN, "", or of course, false.
The problem is that you are updating i inside the loop as well as for the loop itself. This means you need to look at both updates to see what really happens to i. Here are the steps unrolled:
for(var i=0; i<=10; i++){ ...
// i = 0 here
console.log(i += i);
// logged 0 += 0 (0)
// now i will be incremented to 1
console.log(i += i);
// logged 1 += 1 (2)
// increment i to 3
console.log(i += i);
// logged 3 += 3 (6)
// increment i to 7
console.log(i += i);
// logged 7 += 7 (14)
// increment i to 15
// ... etc
It looks like you just missed the fact that += is also updating the i inside the loop, not just from the ++ incrementor.
This is what your code does:
1. i starts with 0, then you assign to it 0 + 0. console logs i as 0
2. i increments to 1, then you assign to it 1 + 1. console logs i as 2
3. i increments to 3, then you assign to it 3 + 3. console logs i as 6
4. i increments to 7, then you assign to it 7 + 7. console logs i as 14
Note that i += i is not the same as i += i + i, but as i = i + i. It is an assignment, and the value returned is the new value of i.
I'm working through eloquent javascript and I don't understand this bit of code
for (var current = 20; current % 7 != 0; current++)
;
console.log(current);
It states that it checks for the first number greater than 20 that is divisible by 7 and console.log() would produce 21.
But I read that as start at 20, check if current divided by 7 has no remainder to see when we break the loop. But straight away 20 mod 7 == 6 meaning it does not equal 0 or (20 % 7 != 0).
So shouldn't the for loop break straight away and console.log(current) produce 20? What am I missing here?
A loop continues as long as the condition is met.
20 % 7 != 0 // 6 != 0 is true, so condition is met and loop continues
21 % 7 != 0 // 0 != 0 is false, so condition fails and loop halts
"... check if current divided by 7 has no remainder"
No, it's "check if current divided by 7 does NOT have no remainder".
I think the negative condition is throwing you. Basically, you need to ask if the condition is a true statement.
So if I'm the condition, and you're the loop, and I say "six does not equal zero", you would say "that's true", so you would agree to let the loop continue.
But then if I say "zero does not equal zero", you would say "that's false", and would halt the loop.
A clearer condition would be "check if current divided by 7 does have a remainder". No double negative, so it could be written as:
for (var current = 20; current % 7; current++) ;
or as:
for (var current = 20; current % 7 > 0; current++) ;
Nothing is wrong here. Simply change the ; line to this line, and you'll get the idea:
for (var current = 20; current % 7 != 0; current++) {
console.log('current value is ' + current ' +
' and the mod result is ' + current % 7);
}
var tops = 5;
while (tops > 0) {
for (var spins = 0; spins < 3; spins++) {
alert("Top is spinning!");
}
tops = tops - 1;
}
Doesn't the var = spins loops 2 times each time the var = tops decreases by one until it gets to the value of 1? Wouldn't that code alert 8 times? I don't know why I get the alert 16 times.
You should get the alert 15 times, not 8 or 16.
The values of tops are 5, 4, 3, 2, 1. For each of these values, spins will be set to 0, 1 and 2.
5 (values for tops) X 3 (values for spins) = 15
You can just print to the screen the values of your variables(tops, spins).
Then you'll see that it loops 15 times and you'll see why.
Here is the jsFiddle for you:
http://jsfiddle.net/66UuT/
you spins loops for 3 times not 2 times as you are starting it from 0