how to do a for loop in array code example

Example 1: arrays with for loops

int findSmallest(int[] values) {
  int minIndex = 0;  // start with 0th element as min
  for (int i=1; i<values.length; i++) {
    if (values[i] < values[minIndex]) {
      minIndex = i;
    }
  }
  return minIndex;
}

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

Tags:

Misc Example