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.
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
Tried doing this for a class assignment but for whatever reason it is saying the count is not defined. Any suggestions?
var num = [1,2,3,4,5,6,7,8,9,10]
for(var num = 0; count < 11; num++) {
if(num % 3 ===0);
console.log(num);
}
I think you mean to use the num variable instead of count.
for(var num = 0; num < 11; num++) {
You are defining the 'num' variable. Setting it to 0 and then running the 'for' loop, adding 1 to 'num' for each loop until 'num' is no longer < 11.
try this...
var num = [1,2,3,4,5,6,7,8,9,10];
for (var count = 0; count < num.length; count++) {
if (num[count] % 3 == 0)
alert(num[count]);
}
Typically, Javascript for loops will have this format:
for (i = 0; i < 11; i++) {
//i = 0 > starting index
//i < 11 > ending index
//i++ > index increment
}
The reason why you ran into your error is because count is never defined as a variable, whereas the variable 'i' in my example was defined when I set the value of i=0.
Instead of thinking that you are looping through the integers within the num array, think of it like you're looping through the indexes of num. So within every loop, the i variable will represent which index of the array you're currently focusing on.
Helpful tips:
make sure you utilize num.length to get the ending index of your for loop
Use indexes to reference integers in an array: num[0] == 1,
num[1] == 2, num[2] == 3 ...
I made a code to extract every odd numbers from one number, and it works for numbers that are not too long such as "1341" (which give me the numbers "1,13,1341,341,41,1") but oddly doesn't work for very long numbers.
function solve(s) {
var newarray = [];
for (var i = 0; i <= s.length; i++) {
for (var j = 0; j <= s.length; j++) {
var slicing = s.slice(i, j);
if (slicing % 2 !== 0) {
newarray.push(slicing);
}
}
}
return newarray.length;
}
Despite putting s.length, it slices until a certain point. For example:
With "93711892377292643581488317", it slices until "9371189237729", then when it starts from 3 it slices until "93711892377292643" (until the next odd number)
With "65266112954758467", from the start it slices until "6526611295475", then when it starts from 5, it slices until "65266112954758467" (until the next odd number).
What's going on?
slicing % 2 doesn't work properly when slicing is large. Javascript treats large numbers as floating-point numbers, which means it's not accurate to know the value to the nearest integer - in binary, the units bit becomes 0, so it's a multiple of 2.
You want to count all odd numeric substrings within a numeric string.
First, consult the documentation of str.slice(beginIndex[, endIndex]).
Then, in order to gain a better understanding of your code, it is helpful to slowly iterate through a few steps of your loops and write down the expected vs. the observed output.
I recommend to use the debugger built into all modern browsers:
Add a debugger; statement into the inner for-loop:
function solve(s) {
var newarray = [];
for (var i = 0; i <= s.length; i++) {
for (var j = 0; j <= s.length; j++) {
var slicing = s.slice(i, j);
debugger; // <-- we want to break here and check our values
if (slicing % 2 !== 0) {
newarray.push(slicing);
}
}
}
return newarray.length;
}
Press [F12] and run this code in your browser's console for some exemplary input.
The debugger tab should now pop up. Press [F8] to step through your code and keep track of the value of your slicing variable.
You will probably notice that slicing is empty at the beginning. You should start your inner loop from j = i + 1 to fix that.
Also, you might notice that your i iterates one time too many, so that slicing is empty during the final iterations of the inner for-loop. You need to terminate your outer loop one step earlier.
Then, for the problematic input "93711892377292643581488317" you will notice that large numeric slices such as "93711892377292643" will not be recognized as odd. "93711892377292643" % 2 evaluates to 0 instead of 1. In order to understand this, you need to know that JavaScript numbers are internally represented as limited precision floating point values. If you put 93711892377292643 into your browser console, it will evaluate to 93711892377292640 - an even number! JavaScript can only handle integer numbers up to Number.MAX_SAFE_INTEGER == 9007199254740991 without introducing such truncation errors.
Now, how to solve this issue? Well, a number is odd if and only if the last digit is odd. So we don't have to inspect the full number, just the last digit:
function solve(s) {
var newarray = [];
for (var i = 0; i < s.length; i++) {
for (var j = i; j < s.length; j++) {
var digit = s.slice(j, j + 1);
if (digit % 2 !== 0) {
var slicing = s.slice(i, j + 1);
newarray.push(slicing);
}
}
}
return newarray.length;
}
console.log(solve("1234567890")); // 25
Once you have sufficient understanding of this code, you could start improving it. You could for example replace the newarray with a simple counter, as you are only interested in the number of off digits, not the digits themselves.
A faster solution could be written down as follows:
function solve(str) {
let count = 0;
for (let i = 0; i < str.length; i++) {
if (str[i] % 2) count += i + 1;
}
return count;
}
console.log(solve("1234567890")); // 25
Or, written in a more declarative way:
const solve = (str) =>
str.split('').reduce((count, chr, i) => chr % 2 ? count + i + 1 : count, 0);
console.log(solve("1234567890")); // 25
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
What would be the difference between
var nums = [];
for (var i = 0; i < 10; ++i) {
nums[i] = i+1;
}
and
var nums = [];
for (var i = 0; i < 10; i++) {
nums[i] = i+1;
}
In the for loop, i = 0, but in the first iteration, would nums[i] = nums [0] or nums [1] since we are using ++i? How would the first iteration be different if i++ were used instead?
Update: For this particular for loop it doesn't matter. However, I'm interested to see a for loop where ++i vs i++ matters.
They would be exactly the same; ++i and i++ have the same effect on i, but the value of each expression is different; in this context, since the value is ignored, the code behaves the same.
As an example where switching between the two would matter, here is some truly awful code:
for ( var i=0; i++ < 10; )
++i increments before the "return", i++ increments after
var i = 0;
i++; //=> 0
i; //=> 1
var j = 0;
++j; //=> 1
j; //=> 1
For the purposes of your for loop, it doesn't make a difference.
In for loops, there is no difference. The difference between ++i and i++ is the value returned by the expression, but the expression is evaluated after each pass of the loop and you ignore the value.
There is no difference between the two. The incremented value will be ignoreed as it will happen at the end of the loop.
EDIT:
It makes no difference in the for loop if you write
for (var i = 0; i < 10; ++i) {
or
for (var i = 0; i < 10; i++) {
You will get the same results in both the cases. The reason why most of the people use i++ or better to say why i++ is more popular over ++i in a for loop is probably because people come from a habit of using i++ which was majorly used in C. Also to note that in C++ you can write your own version of ++ operator.
They are the same. The increment occurs at the end of the body of the loop.
i.e. you can view the loop as
var i = 0;
while (i < 10) {
... Body of loop
i++ or ++i;
}