Java Program for Linear search in an array

This Program will takes three input for the size of array for array Number to search in array Explanation In this program loop will g
Admin
Java Program for Linear search in an array

This Program will takes three input 
  1. for the size of array
  2. for array 
  3. Number to search in array
Explanation 
In this program loop will go upto the value of n-1 or i<n then m is compared to value of arr[i] if the value is in array then it return the value of i else -1;

Sample Input 1
5
11 12 13 14 15 
14
Sample Output 1
3
Sample Input 2
3
1 4 6
4
Sample Output 2
1
Program
import java.util.*;
public class Main {
    public static void main(String args[]) {
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        int[] arr=new int[n];
        for(int i=0;i<n;i++)
        {
            arr[i]=sc.nextInt();
        }
        int m=sc.nextInt();
        System.out.println(linearsearch(arr, m));
    }
    public static int linearsearch(int []arr,int m) 
    {
        for(int i=0;i<arr.length;i++)
        {
            if(arr[i]==m)
            {
                return i;
            }
        }
        return -1;
    }
}

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.