Programming Examples
Cpp program to linear search an element in an array using function
Write a cpp program to search an element in an array using function
Solution
#include<iostream>
using namespace std;
int Lsearch(int[],int,int);
int main(){
int arr[50],ITEM,index,n;
cout<<"Enter the desired array size";
cin>>n;
cout<<"Enter the elements";
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
cout<<"Enter the element to be searched for :";
cin>>ITEM;
index=Lsearch(arr,n,ITEM);
//cout<<" Index is: "<< index;
if(index==-1)
{
cout<<" Element cannot be found"<<endl;
}
else
{
cout<<"Element found at index "<<index<<",position "<<index+1<<endl;
return 0;
}
}
int Lsearch(int arr[],int size, int item)
{
for(int i=0;i<size;i++)
{
if(arr[i]==item)
{
return i;
}
}
return -1;
}
Output
Enter the desired array size 5
Enter the elements
1
3
45
67
23
Enter the element to be searched for : 67
Element found at index 3,position 4