Array Examples

Searching For an Int in and Array of Ints

Consider the following block of code:

int[] array = new int[5];            // All elements initially 0
array[0] = 1;
array[1] = 3;
array[2] = 5;

boolean found = search(array, 3);    // found is true
found = search(array, 2);            // found is false
found = search(array, 0);            // found is true

Write a method named search that has two parameters.  The first parameter is a reference to an array of integers and the second parameter is an integer.  The method returns true if the value of the second argument is an element in the array referenced by the first.  Otherwise it returns false.

private static boolean search(int[] array, int num) {
    boolean found = false;
    for(int i = 0; i < array.length; i++) {
        if (array[i] == num) {
            found = true;
            break;
        }
    }
    return found;
}

Adding Unique Elements to an Array Using Search

Write a block of code that repeatedly asks the user to enter an integer until the user has entered 5 different numbers.

Scanner sc = new Scanner(System.in);
int[] array = new int[5];
int numElements = 0;

while (numElements < 5) {
    System.out.println("Please enter an integer:");
    int num = sc.nextInt();
    boolean found = search(array, num);
    if (!found) {
        array[numElements] = num;
        numElements++;
    }
}

Searching For a String in an Array of Strings

Consider this code:

String[] array = new String[5];
array[0] = "One";
array[1] = "Two";
array[2] = "Tee";

boolean found = search(array, "Tee");   // found is true
found = search(array, "Red");           // found is false
found = search(array, null);            // found is false

Write a method named search that has two parameters.  The first parameter is a reference to an array of Strings and the second parameter is a reference to a non-null String.  The method returns true if the String referenced by the second parameter is in the array referenced by the first parameter. Otherwise it returns false.

boolean search(String[] array, String word) {
    for(int i = 0; i < array.length; i++) {
        if (array[i] == null) {
            return false;
        }
        if (array[i].equals(word)) {
            return true;
        }
    }
    return false;
}

© 2017 – 2020, Eric. All rights reserved.