Answers for "how to use array in for loop"

5

for loop on a array

var array = [1, 2, 3, 4, 5];
// made an array

for (var i = 0; array[i]; i++) // browse your array with this simple condition on index
	console.log('element '+i+' = '+array[i]);

//output:
element 0 = 1
element 1 = 2
element 2 = 3
element 3 = 4
element 4 = 5
Posted by: Guest on August-04-2021
1

loop an array in javascript

let array = ["loop", "this", "array"]; // input array variable
for (let i = 0; i < array.length; i++) { // iteration over input
	console.log(array[i]); // logs the elements from the current input
}
Posted by: Guest on May-18-2020
0

arrays with for loops

// Given an array of booleans representing a series
// of coin tosses (true=heads, false=tails),
// returns true if the array contains anywhere within it
// a string of 10 heads in a row.
// (example of a search loop)
public boolean searchHeads(boolean[] heads) {
  int streak = 0;     // count the streak of heads in a row
  
  for (int i=0; i<heads.length; i++) {
    if (heads[i]) {   // heads : increment streak
      streak++;
      if (streak == 10) {
        return true;  // found it!
      }
    }
    else {            // tails : streak is broken
      streak = 0;
    }
  }
  
  // If we get here, there was no streak of 10
  return false;
}
Posted by: Guest on May-15-2020
0

arrays with for loops

// For-All
// Do something for every element
public void forAll(int[] nums) {
  for (int i=0; i<nums.length; i++) {
    System.out.println( nums[i] );
  }
}
Posted by: Guest on May-15-2020
0

arrays with for loops

// Another way to write search that combines
// the "end of array" and "found" logic in one
// while loop. As a matter of style, we prefer
// the above version that uses the standard
// for-all loop.
public int searchNotAsGood(int[] nums, int target) {
  int i = 0;
  while (i<nums.length && nums[i]!=target) {
    i++;
  }
  // get here either because we found it, or hit end of array
  if (i==nums.length) {
    return -1;
  }
  else {
    return i;
  }
}
Posted by: Guest on May-15-2020

Code answers related to "how to use array in for loop"

Code answers related to "Javascript"

Browse Popular Code Answers by Language