From 0c05a4eda3caf0f045dfb137269d7f0742f7dc7c Mon Sep 17 00:00:00 2001 From: NandiniVar <92244676+NandiniVar@users.noreply.github.com> Date: Fri, 7 Oct 2022 16:19:25 +0530 Subject: [PATCH] Create First_and_last_occurance.cpp --- cpp/First_and_last_occurance.cpp | 37 ++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 cpp/First_and_last_occurance.cpp diff --git a/cpp/First_and_last_occurance.cpp b/cpp/First_and_last_occurance.cpp new file mode 100644 index 0000000..8809227 --- /dev/null +++ b/cpp/First_and_last_occurance.cpp @@ -0,0 +1,37 @@ +#include + +using namespace std; + +int firstOcc(int arr[],int idx,int n,int key) +{ + if(idx == n) + return -1; + + if(arr[idx] == key) + return idx; + + return firstOcc(arr,idx+1,n,key); +} + +int lastOcc(int arr[],int idx,int n,int key) +{ + if(idx == n) + return -1; + + int last = lastOcc(arr,idx+1,n,key); + + if(last != -1) + return last; + + if(arr[idx] == key) + return idx; + + return -1; +} + +int main() +{ + int arr[] = {4,2,5,1,2,8,2,0}; + cout<<"1st occ: "<