for(i code example
Example 1: javascript for loop
var colors=["red","blue","green"];
for (let i = 0; i < colors.length; i++) {
console.log(colors[i]);
}
Example 2: javascript loop
let array = ["foo", "bar"]
let low = 0; // the index to start at
let high = array.length; // can also be a number
/* high can be a direct access too
the first part will be executed when the loop starts
for the first time
the second part ("i < high") is the condition
for it to loop over again.
the third part will be executen every time the code
block in the loop is closed.
*/
for(let i = low; i < high; i++) {
// the variable i is the index, which is
// the amount of times the loop has looped already
console.log(i);
console.log(array[i]);
} // i will be incremented when this is hit.
// output:
/*
0
foo
1
bar
*/
Example 3: for in loop javascript
function diagonalDifference(arr) {
// Write your code here
// return (arr); 11,2,4,4,5,6,10,8,-12
let n = arr.length;
let pri,sec = 0;
pri = sec = 0; //initialize both diagonal sum to 0
for (let i= 0; i < n; i++) {
//console.log( "PRI(arr)= ", i,i);
//console.log( arr[i][i]);
//console.log( "SEC(arr)= ", i,n-i-1);
//console.log( arr[i][n-i-1]);
pri += arr[i][i];
sec += arr[i][n - i - 1];
}
// return |x| is the absolute value of x
if(pri==sec){
return (0);
}else {
if (pri>sec){
return (pri-sec);
}else{
return (sec-pri);
}
}
}