Skip to content

Commit 8188e9b

Browse files
authored
Merge pull request #703 from siddhi-244/Siddhi/last-index
Added last index of a number in array
2 parents 59db01b + 77d90eb commit 8188e9b

File tree

1 file changed

+40
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)