Search code examples
javaarrayslinear-search

Java - Searching an element in a random array


I executed the following code:

import java.util.Scanner;

public class Linear_Search {

    public static void main(String[] args) {
        int arr[] = new int[20];
        for(int i = 0; i < arr.length; i++) {
            arr[i] = (int)(Math.random() * 10) + 1;
        }
        System.out.print("Array is: ");
        for(int i : arr)
            System.out.print(arr[i] + " ");

        //int arr[]= {1,2,4,5,6,7,8,43,6,4,2,6,8,3};
        System.out.println();
        System.out.println("Enter the number you want to search");
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();

        boolean found = false;

        String indices = "";

        for(int i = 0; i < arr.length; i++) {
            if(num == arr[i]) {
                found = true;
                indices = indices + i + ", ";
            }
        }
        if(found == false) {
            System.out.println(num + " does not exist");
        }
        else {
            System.out.println(num + " found at index: " + indices.substring(0, indices.length() - 2));
        }

        sc.close();
    }
}

Output:

Array is: 3 3 1 2 8 1 2 2 3 1 3 3 7 1 7 3 1 3 8 3

Enter the number you want to search

2 

2 found at index: 0, 1, 8 ,15

Why is this displaying random indices as answers. The code works fine when i use a custom array like the one that is commented in the code. Is it related to explicit cast on Math.random() or something else?


Solution

  • You are mislead by the loop printing the array, which doesn't really print the array elements.

    Change:

    for(int i : arr)
        System.out.print(arr[i] + " ");
    

    to:

    for(int i : arr)
        System.out.print(i + " ");
    

    and you'll see the actual array values.

    When you iterate over an array with the enhanced for loop, you are iterating over the array values not over the array indices.