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

Latest Current Affairs 2024 Online Exam Quiz for One day Exam Online Typing Test CCC Online Test 2024 Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Sarkari Exam Quiz