The following code (looping from 10 to 1) doesn't run in javascript and I can't figure out why. Any advice?
for (var x = 10; x >= 1; x--){
console.log(x);
}
The test in a loop says when to keep looping, not when to stop. When your loop starts, x = 10, so x == 1 is false, and the loop stops immediately.
It should be:
for (var x = 10; x >= 1; x--)
you are setting x = 10, then looping while x == 1, which it isn't so you never loop. You should use "x > 0". The test in the loop is "loop as long as this condition is true".
you are using for loop . for for loop syntax is :
for (statement 1; statement 2; statement 3) {
code block to be executed
}
Statement 1 is executed before the loop (the code block) starts.
Statement 2 defines the condition for running the loop (the code block).
Statement 3 is executed each time after the loop (the code block) has been executed.
so according to yours code :
for (var x = 10; x == 1; x--){
console.log(x);
}
it will first assign x to 10 then it will check condition which is x==1 it will return false and loop will stop. so current version will be:
for (var x = 10; x >= 1; x--){
console.log(x);
}
That's not working because the syntax is not correct. It should be:
for (var x = 10; x >= 1; x--){
console.log(x);
}
The x==1 expression is the stopping condition of the loop and, when it's false, loop stops.
Related
I found the code for solving this problem, but I cannot figure out the logic of the solution.
let n = 10;
nextPrime:
for (let i = 2; i <= n; i++) {
for (let j = 2; j < i; j++) {
if (i % j == 0) continue nextPrime;
}
alert( i );
}
I can't understand how the second for works, if it has an increment like the first, then the result should have been all numbers from 2 to 10, since the beginning of both for is the same number (2) ..
Can you please explain each iteration, for example why 4 is not displayed?
It’s using label to break the inner loop when it finds number is not prime . Outer loop is iterating the number and inner loop checks if it’s divisible between 2 to number.
Label break
the continue nextPrime used for just continue in the loop to the next iteration without finish all the code inside the loop.
like:
data:
for (let i = 1; i <= 3; i++) {
if(i === 2)
continue data;
console.log(i)
}
here when I get to I equal to 2 the code continue to the next number without continue to the rest of the code
The following code outer layer for loop is only executed once, wonderfully, why?
let x = -5;
let y = -5;
for (; x < 5; ++x) {
for (; y < 5; ++y) {
console.log(x);
}
}
Because once all inner iterations have finished on the first outer iteration, y is 5, so on the next outer iteration, the condition for the inner iteration (y < 5) is false - the inner loop body never runs again.
No! Outer loop gets executed till x reaches 4 i.e. <5.
you are not resetting value of y before going to inner loop so condition of y is not satisfied and hence its not getting executed.
try putting console.log() before inner loop, then you will get idea of iterations happening.
I have a question about how nested loops work in JavaScript.
Imagine I have while() loop ... and inside of that is a for() loop. Each has its own separate ending conditions (see below for a schematic).
My question is this: will the while() loop stop the INSTANT its ending condition is met--even if the for() loop within it is not yet finished? Here is an example.
var i = 0;
while (i < somenumber){
for(var j=0; j < othernumber; j++){
somecode();
i++:
}
}
The code seems to be working, but I want to make sure I understand how these structures are supposed to work. The goal is to get the while loop (and thus also the for loop within) to stop the instant that 'i' has reached 'somenumber', even if j has not yet reached 'othernumber'.
You can use labels and the break command to exit a parent loop directly:
var x = 0, y=0;
b1: {
while (x++ < 5){
b2: {
for(y=0; y < 3; y++){
if (y === 1){
x = 2;
break b1;
}
}
}
}
}
console.log(`x=${x} y=${y}`)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break
I suggest you test the code and see what it does. Here I tested with arbitrary numbers and it seems to show that the while loop does not terminate the instant the condition is met. It lets the job finish. Here's an explanation:
Initially, the condition is true, so it goes into the while loop. Once in the while loop, it doesn't check if the condition is true until the next iteration, meaning it won't stop executing the for loop even if the condition is false. Here's the test code:
var i = 0;
while (i < 5){
for(var j=0; j < 10; j++){
console.log(j + ", iter= " + i);
i++;
}
}
This yields:
0, iter= 0
1, iter= 1
2, iter= 2
3, iter= 3
4, iter= 4
5, iter= 5
6, iter= 6
7, iter= 7
8, iter= 8
9, iter= 9
From the output above, we see the for loop doesn't end. It keeps on going because, although the while loop's condition is false, it doesn't check if it's true until the next iteration, allowing the for loop to finish.
I tested it for you:
var i = 0;
while (i < 10){
for(var j=0; j < 12; j++){
somecode(j);
i++;
}
console.log('i',i);
}
function somecode(j) {
console.log('in the for loop', j);
}
The entire for loop is executed, and then the final console.log in the while loop is evaluated.
Each loop will check the condition at the end of the current iteration (when the loop reaches the closing bracket). The only way to stop the while loop inside the for loop is to make something like this:
for(var j=0; j < othernumber; j++){
somecode();
i++;
if (!(i < somenumber)) break; //it exits the for loop
}
When you exit the for loop and reach the closing bracket of the while loop, it will check the while condition and exit from the loop
After experimenting with the use of "i++" and "++i" I could not find a difference between their results when used in a 'for' loop.
For example:
for (var i = 0; i < 10; ++i) {
console.log(i);
}
would yield:
0
1
2
3
4
5
6
7
8
9
Shouldn't it be printing out the numbers from 1 to 10, as the iterator is being incremented before console.log(i) executes?
The "increment step" is executed after the loop body is executed. Given
for (a;b;c) {
d
}
the execution order is
a // initialize
b // condition - first iteration
d // loop body
c // "increment"
b // condition - second iteration
d // loop body
c // "increment"
...
b // condition - last iteration - break
So in your case:
var i = 0;
i < 10;
console.log(i); // 0
++i;
i < 10;
console.log(i); // 1
++i;
// ...
i < 10;
The difference between i++ and ++i is only relevant if you do something with the return value, which you don't.
Because the last clause of the for loop only happens at the end of the loop, as its own statement, the behavior of your loop is not affected by this difference. However, imagine you did something like this:
for (var i = 0; i < 10;) {
console.log(++i);
}
for (var j = 0; j < 10;) {
console.log(j++);
}
Then you'd see a difference. The first example would produce numbers 1-10, whereas the second would produce numbers 0-9. That's because f(j++) is equivalent to j += 1; f(j);, whereas f(++i) is more like f(i); i += 1;.
May I advise that while your testing is fine on whatever platform you are using, the standard construct is i++
Always code the standard and isolate various platforms and make exceptions as needed !!!
i++ Simply means increment 'i' by one.
I can speculate ++i means to add 'i' to itself eg if 'i' was 2 then it would then increment to 2,4,8,16,32
But I have never seen ++i used in many places.
This question could also be (depending on how you look at it) - How to use a for loop to do a basic math operation that adds up the sum of the multiples of 3
So I am doing Problem 1 of Project Euler.
I've (already) hit a steel-reinforced wall. I could use some help - with just a specific portion of the problem please (I am not looking for just an answer to the problem, but rather, an answer to my specific problem so I can carry on with trying to solve the remainder problem using any answer you guys provide me here)...
Anyways.
I (think I) created a for loop that will give me the multiples of 3. However, I'm trying to store the result of each iteration of the for-loop so that it adds up to the sum of those multiples i.e. I'm trying to store the result from each iteration of the loop - whether it be into an array or into a variable that takes the sum of the multiples - it doesn't matter to me - I wouldn't mind learning both methods.
I'm sure this sounds kind of confusing so let me paint my picture w/ an example...
I have a for-loop:
for (i = 1; i <= 3; i++) {
var x = 0;
x += (i * 3);
WHAT DO I DO NEXT????
^ So I would think that this gives me x with a value of 3 upon the 1st iteration of the loop, x with a value of 9 on the 2nd loop, and x with a value of 18 on the final loop. That's correct, right? (if this were returning 18 I don't think I would need to store the values of each iteration into an array)
1st iteration:
i = 1; x = 0
Original equation...
(i * 3) + x
So...
(1 * 3) + (x = 0) = 3
So after completion of the 1st loop, x has a value of 3, right???
(Question: How would I store this value of x (which is 3) - how would I store it in an array while in this stage of the for loop?)
2nd iteration of loop:
i = 2; x = 3
(2 * 3) + (x = 3) = 9
(same question as before: how would I add this value to an array?)
3rd iteration:
i = 3; x = 9
(3 * 3) + (x = 9) = 18
Q: shouldn't this be the final value of x upon completion of the for loop??? For some reason, when I run the code, the final value of x is 9, and not 18
So, basically I am trying to add the sum of the 3 values...But what do I do next? I thought my for loop would add the result of the equation after each loop to x, but instead of ending up w/ 18 (the sum of 3 + 6 + 9), x's value was 9???
Should I use an array? If so, I'm thinking I could add the return value to an array, but I'm not sure how to add the result of each iteration of the loop to an array. Maybe the following?...
for (i = 1; i <= 3; i++) {
var array = [];
x = 0;
x += (i *3);
array.push(x);
};
^ I tried running that in jfiddle, but it would only add the last value of x (9) into the array... So how would I add the value of x to an array after each iteration of the for loop??? And I'm not seeing what's wrong with my for-loop to where it's returning a value of x as 9?
Also, I'm assuming the euler problems get significantly more difficult as we progress? If so, I've got a TON of work/practice to do....
THANKS IN ADVANCE...
Just create the array once, and push the result at each iteration to the array:
var array = [];
for (i = 1; i <= 3; i++) {
var x = 0;
x += (i *3);
array.push(x);
}
Or for that matter, just use this:
var array = [];
for (i = 1; i <= 3; i++) {
array.push(i *3);
}
Or to simply get the sum of the factors, use this:
var x = 0;
for (i = 1; i <= 3; i++) {
x += i *3;
}
You are declaring var x = 0 and var array = [] at every step of the loop, try something like:
var array = [], x = 0;
for (i=1; i<4; i++){
x += (i*3);
array.push(x);
}
You can use like this:
and you have to define X out of the loop
var array = [],
x = 0;
for (i=1; i<4; i++){
x += (i*3);
array.push(x);
}