Pages

Friday, May 23, 2025

First Occurence using Recursion in C++

 #include <iostream>

#include <vector>
using namespace std;

int firstOccur(vector<int> arr, int i, int target) {
    if(i==arr.size()) {
        return -1;
    }


    if(arr[i] == target)
    {
        return i;
    }


    return firstOccur(arr, i+1, target);
}

int main() {
    vector<int> arr = {1, 2, 3, 3, 3, 4};
    cout << firstOccur(arr, 0, 4);
    return 0;
}

No comments:

Post a Comment

Stack using Linked List – Partial (University Exam Topic)

 #include <iostream> using namespace std; struct Node {     int data;     Node* next; }; class Stack {     Node* top; public:     Stac...