• Post author:
• Post category:C Programs

If you are looking for a program for Linear search in c, c++ and java then you are at thr right article. Find the linear search implementation in c, c++ and java languages.

In linear search we are comparing a key element with the elements of array in each iteration, If we find the key element in the array then we can stop searching or we can continue for duplicates.

Array is not required to be sorted for linear search technique.

Linear search algorithm is in-place algorithm. It does not require any extra space .

## Required coding Concepts for Linear search in c, c++ and java

• Data types in C , C++ and Java.
• Basic input and output.
• Array Concept in C, C++ and Java
• Comparisn of two data elements in C, C++ and Java

## Linear search algorithm

• Step 1: Initialize array and key elements.
• Step 2: Start comparing element of array with key element
If element is found then note down its index stop searching.
• Step 3: End

## Linear search in c

Note: Follow-up comment lines.

``````#include <stdio.h>
#include<stdlib.h>
int main(int argc, char const *argv[])
{
//declare an array
int arr;
int n,key;
printf("\nEnter number of array elements\n");
scanf("%d",&n);
printf("\nEnter array elements");
for( int i=0 ; i<n ; i++ )
{
scanf("%d",&arr[i]);
}
printf("\nEnter key to find\n");
scanf("%d",&key);
for( int i=0 ; i<n ; i++ )
{
//check if that key element is equal to array element
if( key == arr[i] )
{
printf("\n%d found at %d\n",key,(i+1));
return 0;
}
}

return 0;
}``````

## Linear search in C++

Note: Follow-up comment lines.

``````#include <iostream>
using namespace std;
int main(int argc, char const *argv[])
{
//declare an array
int arr;
int n,key;
cout<<"\nEnter number of array elements\n";
cin>>n;
cout<<"\nEnter array elements";
for( int i=0 ; i<n ; i++ )
{
cin>>arr[i];
}
cout<<"\nEnter key to find\n";
cin>>key;
for( int i=0 ; i<n ; i++ )
{
//check if that key element is equal to array element
if( key == arr[i] )
{
cout<<"\n"<<key<<" found at "<<i+1<<"\n";
return 0;
}
}

return 0;
}``````

## Linear search in Java

Note: Follow-up comment lines.

``````import java.util.Scanner;

public class linear_search {
public static void main(String[] args)
{
System.out.println("Enter no of elements");
Scanner stdin=new Scanner(System.in);
int n=stdin.nextInt();
int[] arr=new int[n];
System.out.println("Enter elements");
for( int i=0 ; i<n ; i++ )
{
arr[i]=stdin.nextInt();
}
System.out.println("Enter key to find");
int key=stdin.nextInt();
for( int i=0 ; i<n ; i++ )
{
if( arr[i] == key )
{
System.out.println(key+" Found at"+(i+1));
System.exit(0);
}
}