java examples + arrays + loops

Example 1: how to use for loop for array in java

// Java program to iterate over an array 
// using for loop 
import java.io.*; 
class GFG { 
  
    public static void main(String args[]) throws IOException 
    { 
        int ar[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; 
        int i, x; 
  
        // iterating over an array 
        for (i = 0; i < ar.length; i++) { 
  
            // accessing each element of array 
            x = ar[i]; 
            System.out.print(x + " "); 
        } 
    } 
}

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;
}

Example 3: 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 4: arrays with for loops

String[] words = new String[] { "hello", "foo", "bar" };
int[] squares = new int[] { 1, 4, 9, 16 };

Tags:

Java Example