Skip to content

Commit c6cc552

Browse files
authored
Added first index of an element in array
1 parent 3379d2d commit c6cc552

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/*Program to find first index of a number in array*/
2+
#include <iostream>
3+
using namespace std;
4+
int firstIndex(int arr[],int n,int x){
5+
if(n==0){ //if size of array is 0
6+
return -1;
7+
}
8+
if(arr[0]==x){ //if the element is found on first index
9+
return 0;
10+
}
11+
int ans=firstIndex(arr+1,n-1,x);//recursion
12+
if(ans==-1){
13+
return -1;
14+
}
15+
else{
16+
return ans+1;
17+
}
18+
}
19+
20+
int main() {
21+
int n,x,a[200];
22+
cin>>n;
23+
for(int i=0;i<n;i++){
24+
cin>>a[i];
25+
}
26+
cin>>x;
27+
cout<<firstIndex(a,n,x);
28+
29+
}
30+
/*Example
31+
Input:
32+
5
33+
5 5 6 7 9
34+
5
35+
Output:
36+
0
37+
*/

0 commit comments

Comments
 (0)