java + programs + arrays + loops code example

Example 1: arrays with for loops

Account[] accounts;

// 1. allocate the array (initially all the pointers are null)
accounts = new Account[100];	

// 2. allocate 100 Account objects, and store their pointers in the array
for (int i=0; i<accounts.length; i++) {
  accounts[i] = new Account();
}

// 3. call a method on one of the accounts in the array
account[0].deposit(100);

Example 2: 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;
}

Example 3: arrays with for loops

// Find-Max variant
// Use very small number, Integer.MIN_VALUE,
// as the initial max value.
public int findMax2(int[] nums) {
  int maxSoFar = Integer.MIN_VALUE;  // about -2 billion

  // Look at every element
  for (int i=0; i<nums.length; i++) {
    if (nums[i] > maxSoFar) {
      maxSoFar = nums[i];
    }
  }
  
  return maxSoFar;
}

Tags:

Misc Example