Print even number using for loop without using if condition - javascript

I have an easy drill to print all the even numbers between 1-1000.
I want to set the condition in the line of the loop and not below it..
This is what I've tried:
for (let i = 1; i <= 1000 && i % 2 == 0 ; i++) {
document.write(i + " ");
// I dont want the condition here !!!
}
I searched the forum and tried this too:
for (let i = 1;( (i <= 1000) && (i % 2 == 0) ); i++) {
document.write(i + " ");
}
It looks like the same code I think, but there is nothing in the console when I run the code..

The test condition in the loop header determines whether the loop will continue to iterate. Because the first value of i is 1, and 1 is not even, the loop body is never run.
The whole test expression must be true (well, "truthy") for the loop not to stop. Therefore, you cannot place the evenness test in the loop header. It must be a separate test inside the loop body.
Now, you could do this without a test by starting the iteration at 2 instead of 1 and adding 2 on each iteration. Then you don't need to test for evenness at all:
for (let i = 2; i <= 1000; i += 2)
document.write(i);

Related

Don't understand why my for loop code isn't working

I was playing with the break and continue keyword but I notice in chrome console this code doesn't work
for (let i = 0; i > 5; i++) {
console.log(i);
} //this will print all number from 1 to 5 but console showing undefined
However I tried changing i = 5 or i === 5 still it doesn't work
But when I changed it to i < 5 then it yields correct result.
Why is that?
your condition is i > 5. At the beginning i = 0 so it will not run ever.
put i < 5
Please check following diagram
Condition getting false on the first time so code block won't execute
i<5 indicates that the for loop will run as long as i is less than 5. i>5 indicates that 0 is less than 5 (let i = 0). So the correct program should be -
for (let i = 0; i <= 5; i++) {
console.log(i);
}

visual studio code doesn't run for-loop when condition is set to i = parameter

i wanted see what the output will be if the condition for executing the code block is i = num. when i run the code, vs code terminal just shows node (path of my file) and i subsequently cannot execute any code from any file again. i must restart vs code and change the condition to i < num. why is this so? running the code in the code snippet here also seemingly crashes the page.
is this an infinite loop? however i don't see how it is an infinite loop as the condition to run the code is i=num. if i =/= num, shouldn't an error be returned instead of crashing vs code?
function FirstFactorial(num) {
let solution = 1
for (let i = 1; i = num; i++){
solution *= i
}
return solution;
}
console.log(FirstFactorial(5))
One thing to address. The second parameter for the for loop should be a condition.
i = num
is not a condition.
If you want to compare those variables you can use the triple ===
the issue is the i = num in your:
for (let i = 1; i = num; i++){
you want i <= num for the for loop to iterate.
for (let i = 1; i <= num; i++){
solution *= i
}
The for loop iterates while the second block i <= num evaluates to
true.
As soon as its false it will break out of the for loop,
as 1 != 5 (where num is 5 in your example) having i = num; as your second block evaluates to false right away and the for statement does not run.

Problems with nested loops in Javascript

I'm trying to do a nested loop in javascript, it's my first time doing this kind of things and i have a lot of doubts :(!
I need to get the times a variable is printed or used into a loop, and the first thing that passed through my mind was using .length... And I thought it worked... But it did not, or I don't know if it did.
When i used the length method, i get this in the console: Console Message
That's the value that i need, but i don't know if I can work with it, i don't even know the value's name and it appears like "undefined" :(!
And i just can't use a console.log on the variable out of the loop because it returns just the last value on it, and not specifically the number of times this is printed on.
If you have more doubts, take a look of my code, maybe it can clarify you guys.
function calculatingDays(day, month, year, current_day, current_month, current_year, final_day, callback){
for (k = year; k <= (year + 1); k++){
for (i = current_month; i <= 12; i++){
for (j = current_day; j <= final_day; j++) {
console.log(j.length)
if (j === day && i === month) {break}
}
final_day = new Date(year, i, 0);
final_day = final_day.getDate();
current_day = 1;
if (j === day && i === month) {break}
}
if (j === day && i === month) {break}
}
}
}
What you need is something that can hold the count of times something has occurred. This can best be done by a variable that you can increment. What does this look like?
var counter = 0;
// later on when you find you need to increment the counter
counter = counter + 1;
Then after you're done looping you can do console.log(counter). In your code you want the var counter = 0 to occur right above the first for loop. Where you are currently doing console.log(j.length) is where you increment the counter. Then choose a spot outside of the loop that you want to print it. You have several loops and I'm not sure when you want to print the counter.

Break and Continues

I wonder if someone can clarify something for me. I have a bit of code to check an array for overlapping values depending on different values. Basically its the contents of a google sheet in rows and comumns for this is specifically GAS. What I have at the moment is
var e = [[2,4,3,4,2],[1,5,3,6,2],[2,4,3,4,1],[1,4,3,6,1],[2,4,3,6,5]];
var i; //id of entry to check
var j; //id of element to check
var k; //id of entry to compare
for (i in e){ //2D ARRAY ARRAY
for (k in e){ //ELEMENT TO COMPARE
if (e[i][2] === e[k][2] && e[i][3] === e[k][3] && e[i][0] && e[i][0] >= e[k][0] && e[i][1] <= e[k][1] && e[i][4] <= e[k][4] && i !=k){
e.splice(i,1);
continue;
}
}
}
return e;
I had to add the continue; as otherwise if the last array checked was also marked for splice the code failed. But I assumed break would also work in place of continue but for some reason it does not. I thought break would return to the outside loop but does it permanently break that bit of code?
Thanks people
EDIT: spoke too soon. code still fails even with continue. head scratching continues
continue jumps directly to the next iteration, so:
while(true) {
console.log("a");
continue;
console.log("b");
}
will only log a as it will jump back to the beginnig of the loop if it reaches continue.If you however move continue to the last line of the loop (just as in your code) it does nothing as it would jump to the begining to the loop one line later, so it just skips an empty line.
I thought break would return to the outside loop
Yup, thats what happens and that is actually a good thing as if you removed the element already, it won't make sense to check for other dupes as you don't want to remove it twice.
Now the real problem is that splice changes the indexes, so if you splice out the fourth element, the fith element becomes the fourth element, but the loop continues to the fith element without checking the fourth element again (which is now a different one). Therefore you have to go back by one element before you break:
for(let i = 0; i < e.length; i++) {
for(let k = 0; k < e.length; k++) {
if(i === k) continue; // < good usecase
if(/* equality checks */) {
e.splice(i, 1); // remove the element
i--; // go back by one as we changed the order
break; // exit the inner loop
}
}
}
IMO:
1) I would favor for(const [i, value] of arr.entries() over for..in
2) you will forget what arr[i][2] is very soon, giving proper names to the indexes makes it way more readable:
const [idA, someValueA] = e[i];
const [idB, someValueB] = e[k];
if(idA === idB && someValueA <= someValueB // ...
3) e is a bad name.
You can use a labelled break to break out of nested loops.
eg
var num = 0;
outermost:
for(var i = 0; i < 10; i++){
for(var j = 0; j < 10 ; j++){
if(i == 5 && j == 5){
break outermost;
}
num++;
}
}

Nested Javascript for loops with break and label statements

I'm kinda new to Javascript and currently going over the book Professional Javascript for Web Developers and I came across this code which uses a break statement to exit the current loop and jump to a label named outermost.
Now I understand what break and labels do but I can't wrap my head around why the value ends up being 55 at the end?
Ok so the for loop with var i will loop 4 times then at 5 it breaks out to label:outermost and same with j so the first iteration i = 4 and j = 4 and num = 2. I guess this part confuses me.. at what point does the code stop. My first instinct if I were to code this from scratch is to have an outside variable and set the condition on that. But with the below code I don't get where the control structure lies and the final value. Appreciate any help or to be pointed in the right direction, thanks.
var num = 0;
outermost:
for (var i=0; i < 10; i++) {
for (var j=0; j < 10; j++) {
if (i == 5 && j == 5) {
break outermost;
}
num++;
}
}
alert(num);
This nested loop is emulating an odometer. i is the 10's digit, j is the 1's digit. Every time the 1's digit changes, num is incremented; at the start of each iteration, num contains the odometer's value.
The loop stops when both i and j are 5. At that point, the odometer would read 55, and that's what is in num.
When i was 0 to 4, the innermost loop is executed 50 times. When i = 5, the innermost loop is executed just 5 times until it reached i==5 && j==5 and jumped out. So it's total of 55 times.

Categories

Resources