using for loop java arrays 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
// Search
// Searches through the given array looking
// for the given target. Returns the index number
// of the target if found, or -1 otherwise.
// (classic search-loop example)
public int search(int[] nums, int target) {
// Look at every element
for (int i=0; i<nums.length; i++) {
if (nums[i] == target) {
return i; // return the index where the target is found
}
}
// If we get here, the target was not in the array
return -1;
}