find first and last occurence of a number in an array using recursion in c++
first and last occurence of a number in an array using recursion in c++
#include <iostream>
using namespace std;
int f_occur(int a[],int n,int s,int i){ //s is the required number to be find.
if(a[0]==s){
return i;
}
else{
return f_occur(a+1,n-1,s,i++);
}
}
int l_occur(int a[],int n,int s,int i){ //s is the required number to be find.
if(a[n-1]==s){
return i;
}
else{
i--;
return l_occur(a+1,n-1,s,i--);
}
}
int main()
{
int a[50],n,s,i;
cin>>n>>s;
for(i=0;i<n;i++){
cin>>a[i];
}
if(n!=0){
cout<<"first "<<f_occur(a,n,s,0)<<"last ";
}
else{
cout<<"no array";
}
cout<<l_occur(a,n,s,n-1);
return 0;
}
Comments
Post a Comment