C++ Program to Search Element from Array using Recursion
Write C++ Program to Search Element from Array using Recursion
// CPP Program to Search Element from Array using Recursion
#include <iostream>
using namespace std;
int searching(int A[],int n, int s, int l)
{
if(s <= l - 1)
{
if(A[s] == n)
{
return s;
}
else
return searching(A, n, s + 1, l);
}
return -1;
}
int main()
{
int A[] = {25, 53, 62, 81, 13};
int n, start = 0, result;
int l = sizeof(A) / sizeof(A[0]);
cout << "Array Elements :--> ";
for(int i=0; i<l; i++)
cout << A[i] << " ";
cout << "\nEnter Element to Search :--> ";
cin >> n;
result = searching(A, n, start, l);
if(result == -1)
cout << "\nElement is not present ";
else
cout << "\nElement is present at : " << result;
return 0;
}
Output:
Run 1:
Array Elements :--> 25 53 62 81 13
Enter Element to Search :--> 81
Element is present at : 3
Run 2:
Array Elements :--> 25 53 62 81 13
Enter Element to Search :--> 11
Element is not present