forked from krishnamanojpvr/DSCPP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
17_First_Last_Occ.cpp
67 lines (61 loc) · 1.09 KB
/
17_First_Last_Occ.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
Write a CPP program to find the
first occurrence and last occurrence of an array using recursion
Hint:
take array as {4,2,1,2,2,7} print the first and last ocurrence of 2
Sample Output:
first occurrence is
1
last occurrence is
4
*/
#include <iostream>
using namespace std;
int focc(int a[], int n, int key, int i)
{
if (i == n)
{
return -1;
}
if (key == a[i])
{
return i;
}
return focc(a, n, key, i + 1);
}
int locc(int a[], int n, int key, int i)
{
if (i == n)
{
return -1;
}
int rest = locc(a, n, key, i + 1);
if (rest != -1)
{
return rest;
}
if (a[i] == key)
{
return i + 1;
}
return -1;
}
int main()
{
int a[] = {1,1,1,1,1};
int n = sizeof(a) / sizeof(a[0]);
int key = 1;
int first = focc(a, n, key, 0);
int last = locc(a, n, key, 0);
if (first != -1)
{
cout << "first occurrence is" << endl;
cout << first << endl;
}
if (last != -1)
{
cout << "last occurrence is" << endl;
cout << last - 1<< endl;
}
return 0;
}