top of page

C++ | Linear Search using recursion

In this post, we will learn how to write a C++ Program to implement Linear Search using recursion.

Here’s a simple C++ Program to implement Linear Search using recursion in C++ Programming Language.


Implementation:

#include<iostream>
using namespace std;
 
int recursiveLinearSearch(int array[],int key,int size)
{
 size=size-1;
 if(size <0)
 {
 return -1;
 }
 else if(array[size]==key)
 {
 return 1;
 }
 else
 {
 return recursiveLinearSearch(array,key,size);
 }
}
 
int main()
{
 int size;
 cout<<"\nEnter Size Of Array :: ";
 cin>>size;
 int array[size], key,i;
 
 for (int j=0;j<size;j++)
 {
 cout<<"\nEnter [ "<<j<<" ] Element :: ";
 cin>>array[j];
 }
 
 cout<<"\nThe Array entered is :: \n\n";
 
 for (int a=0;a<size;a++)
 {
 cout<<"Arr[ "<<a<<" ]  =  ";
 cout<<array[a]<<endl;
 }
 
 cout<<"\nEnter any Key To Search in Array :: ";
 cin>>key;
 int result;
 
 result=recursiveLinearSearch(array,key,size--);
 
 if(result==1) {
 cout<<"\nKey Found in Array .\n ";
 } else {
 cout<<"\nKey NOT Found in Array .\n ";
 }
 return 0;
}

Output:

Enter Size Of Array :: 7
Enter [ 0 ] Element :: 1
Enter [ 1 ] Element :: 2
Enter [ 2 ] Element :: 3
Enter [ 3 ] Element :: 4
Enter [ 4 ] Element :: 5
Enter [ 5 ] Element :: 6 
Enter [ 6 ] Element :: 7
The Array entered is ::
Arr[ 0 ] = 1
Arr[ 1 ] = 2
Arr[ 2 ] = 3
Arr[ 3 ] = 4
Arr[ 4 ] = 5
Arr[ 5 ] = 6
Arr[ 6 ] = 7
Enter any Key To Search in Array :: 4
Key Found in Array .
 

Happy Coding!

Follow us on Instagram @programmersdoor

Join us on Telegram @programmersdoor

Please write comments if you find any bug in the above code/algorithm, or find other ways to solve the same problem.

Follow Programmers Door for more.

48 views0 comments

Recent Posts

See All
bottom of page