1.

Find the Target Element in an array.

Answer»

First of all, you will get a number n, which indicates the size of the ARRAY. After that, you will get n more inputs corresponding to each index of the array. Then you will be given a target, for which you have to FIND, at which index of array target is present. Print -1 if target is not present in the array.

Approach:

We will RUN a for loop on the input array and check if the value equivalent to target is present in the array or not.

If the target is found then we will print the index of this target value and return else we will return -1.

import java.io.*;import java.util.*;public class InterviewBit { public static void main(String[] args) throws Exception { Scanner scn = new Scanner(System.in); int n = scn.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = scn.nextInt(); } int target = scn.nextInt(); for (int i = 0; i < arr.length; i++) { if (target == arr[i]) { System.out.println(i); return; } } System.out.println(-1); }}


Discussion

No Comment Found