Share on Google+Share on Google+

Find position of an array element

Advertisement
In this section, you will learn how to find the index of an array element.

Find position of an array element

In this section, you will learn how to find the index of an array element. For this, we have allowed the user to enter the array elements of their choice and also the number whose index value is to be determine. The method get() accept the array values and the element and return the position of the given integer in array. If the given integer is not in the array then it will return -1.

Here is the code:

import java.util.*;

class ArrayExample {
	public static int get(int[] array, int num) {
		for (int i = 0; i < array.length; i++) {
			if (array[i] == num) {
				return (i);
			}
		}
		return (-1);
	}

	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		System.out.println("Enter array values: ");
		int arr[] = new int[5];
		for (int i = 0; i < arr.length; i++) {
			arr[i] = input.nextInt();
		}
		System.out.println("Enter element to find its position: ");
		int element = input.nextInt();
		int index = get(arr, element);
		System.out.println(element + " is found at index : " + index);
	}
}

Output:

Enter array values:
10
20
30
40
50
Enter element to find its position:
30
30 is found at index : 2

Advertisements

Posted on: July 2, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.