Q:

C++ program to find first occurrence of a Number Using Recursion in an array

belongs to collection: C++ programs on various topics

0

C++ program to find first occurrence of a Number Using Recursion in an array

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Algorithm:

Step 1: To solve this using recursion, make a recursion function with inputs, and a variable currIndex to traverse the input array.

Step 2: Base Case: If currIndex == size of the input array, return -1, i.e element not found.

Step 3: If x == input[currIndex], then return currIndex.

Step 4: else return the next call of recursive function with currIndex incremented.

C++ Source Code/Function:

#include<bits/stdc++.h>

using namespace std;

int firstIndex(int input[], int size, int x, int currIndex){
    if(size==currIndex){
        return -1;
    }

    if(input[currIndex] == x){
        return currIndex;
    }

    return firstIndex(input,size,x,currIndex+1);
    
}

int main(){
    int input[] = {9,8,10,8};
    int x = 8;
    int size = 4;

    cout<<firstIndex(input,size,x,0);

    return 0;
}

Output

 
1

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ programs on various topics

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C++ program to find Last occurrence of a Number us... >>
<< C++ program to find number of BSTs with N nodes (C...