Skip to content

Commit f8326e7

Browse files
authored
Merge pull request #473 from siddhi-244/Siddhi/first_index
Added first index of an element in array
2 parents 3379d2d + abfc122 commit f8326e7

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ This repository contains all the popular Competitive Programming questions and I
2626
<li><a href="https://github.com/smv1999/CompetitiveProgrammingQuestionBank/tree/master/Numbers">Numbers</a></li>
2727
<li><a href="https://github.com/smv1999/CompetitiveProgrammingQuestionBank/tree/master/OOPs">OOPs</a></li>
2828
<li><a href="https://github.com/smv1999/CompetitiveProgrammingQuestionBank/tree/master/Passwords">Passwords</a></li>
29+
<li><a href="https://github.com/smv1999/CompetitiveProgrammingQuestionBank/tree/master/Recursion">Recursion</a></li>
2930
<li><a href="https://github.com/smv1999/CompetitiveProgrammingQuestionBank/tree/master/Searching%20Algorithms">Searching Algorithms</a></li>
3031
<li><a href="https://github.com/smv1999/CompetitiveProgrammingQuestionBank/tree/master/Sorting%20Algorithms">Sorting Algorithms</a></li>
3132
<li><a href="https://github.com/smv1999/CompetitiveProgrammingQuestionBank/tree/master/Standard%20Template%20Library">Standard Template Library</a></li>
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)